{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Sorted Merge LCCI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Easy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #LCCI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #array #two-pointers #sorting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #数组 #双指针 #排序"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: merge"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #合并排序的数组"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>给定两个排序后的数组 A 和 B，其中 A 的末端有足够的缓冲空间容纳 B。 编写一个方法，将 B 合并入 A 并排序。</p>\n",
    "\n",
    "<p>初始化&nbsp;A 和 B 的元素数量分别为&nbsp;<em>m</em> 和 <em>n</em>。</p>\n",
    "\n",
    "<p><strong>示例:</strong></p>\n",
    "\n",
    "<pre><strong>输入:</strong>\n",
    "A = [1,2,3,0,0,0], m = 3\n",
    "B = [2,5,6],       n = 3\n",
    "\n",
    "<strong>输出:</strong>&nbsp;[1,2,2,3,5,6]</pre>\n",
    "\n",
    "<p><strong>说明:</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>A.length == n + m</code></li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [sorted-merge-lcci](https://leetcode.cn/problems/sorted-merge-lcci/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [sorted-merge-lcci](https://leetcode.cn/problems/sorted-merge-lcci/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def countBattleships(self, board: List[List[str]]) -> int:\n",
    "        m,n = len(board),len(board[0])\n",
    "        parent = {(x,y):(x,y) for x  in range(m) for y in range(n) if board[x][y] == 'X'}\n",
    "        rank = {(x,y):1 for x  in range(m) for y in range(n) if board[x][y] == 'X'}\n",
    "        self.count = 0\n",
    "        def find(i):\n",
    "            if parent[i] != i:\n",
    "                parent[i] = find(parent[i])\n",
    "            return parent[i]\n",
    "        def merge(i,j):\n",
    "            ri,rj = find(i),find(j)\n",
    "            if ri != rj:\n",
    "                if rank[rj] > rank[ri]:\n",
    "                    ri,rj = rj,ri\n",
    "                parent[rj] = ri\n",
    "                rank[ri] += rank[rj]\n",
    "                self.count -= 1\n",
    "        for i in range(m):\n",
    "            for j in range(n):\n",
    "                if board[i][j] == 'X':\n",
    "                    self.count += 1\n",
    "                    for x,y in [[i+1,j],[i,j-1]]:\n",
    "                        if 0<=x<m and 0<=y<n and board[x][y] == 'X':\n",
    "                            merge((x,y),(i,j))\n",
    "        return self.count"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def beautifulArray(self, n: int) -> List[int]:\n",
    "        ans = []\n",
    "\n",
    "        #触底\n",
    "        if n == 1:\n",
    "            ans.append(1)\n",
    "            return ans\n",
    "\n",
    "        #递归地将子问题解决\n",
    "        left_beautiful_arry = self.beautifulArray((n + 1) // 2)\n",
    "        right_beautiful_arry = self.beautifulArray(n // 2)\n",
    "\n",
    "        #merge:\n",
    "        for val in left_beautiful_arry:\n",
    "            # 将左侧数组映射为奇数\n",
    "            ans.append(val * 2 - 1)\n",
    "        for val in right_beautiful_arry:\n",
    "            # 将右侧数组映射为偶数\n",
    "            ans.append(val * 2)\n",
    "        return ans\n",
    "        \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def beautifulArray(self, n: int) -> List[int]:\n",
    "        ans = []\n",
    "\n",
    "        #触底\n",
    "        if n == 1:\n",
    "            ans.append(1)\n",
    "            return ans\n",
    "\n",
    "        #递归地将子问题解决\n",
    "        left_beautiful_arry = self.beautifulArray((n + 1) // 2)\n",
    "        right_beautiful_arry = self.beautifulArray(n // 2)\n",
    "\n",
    "        #merge:\n",
    "        for val in left_beautiful_arry:\n",
    "            # 将左侧数组映射为奇数\n",
    "            ans.append(val * 2 - 1)\n",
    "        for val in right_beautiful_arry:\n",
    "            # 将右侧数组映射为偶数\n",
    "            ans.append(val * 2)\n",
    "            \n",
    "        return ans\n",
    "        \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def beautifulArray(self, n: int) -> List[int]:\n",
    "        ans=[i for i in range(1,n+1)]\n",
    "        def merge(ans):\n",
    "            if len(ans)==2 or len(ans)==1:\n",
    "                return ans\n",
    "            A=[]\n",
    "            B=[]\n",
    "            for i in range(len(ans)):     \n",
    "                if i%2==0:\n",
    "                    A.append(ans[i])\n",
    "                else:\n",
    "                    B.append(ans[i])\n",
    "            return merge(A)+merge(B)\n",
    "        return merge(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def __init__(self):\n",
    "        self.H = {}\n",
    "\n",
    "    def beautifulArray(self, n: int) -> List[int]:\n",
    "        ans = []\n",
    "\n",
    "        #触底\n",
    "        if n == 1:\n",
    "            ans.append(1)\n",
    "            return ans\n",
    "        if n in self.H:\n",
    "            return self.H[n]\n",
    "\n",
    "        #递归地将子问题解决\n",
    "        left_beautiful_arry = self.beautifulArray((n + 1) // 2)\n",
    "        right_beautiful_arry = self.beautifulArray(n // 2)\n",
    "\n",
    "        #merge:\n",
    "        for val in left_beautiful_arry:\n",
    "            # 将左侧数组映射为奇数\n",
    "            ans.append(val * 2 - 1)\n",
    "        for val in right_beautiful_arry:\n",
    "            # 将右侧数组映射为偶数\n",
    "            ans.append(val * 2)\n",
    "\n",
    "        #放入哈希表\n",
    "        self.H[n] = ans\n",
    "        return ans\n",
    "        \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def dprogramming(self, k, prices):\n",
    "        \"\"\"\n",
    "        :type k: int\n",
    "        :type prices: List[int]\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        if k <= 0 or len(prices) == 0:\n",
    "            return 0\n",
    "        l = [[0 for _ in range(k+1)] for _ in range(len(prices))]\n",
    "        g = [[0 for _ in range(k+1)] for _ in range(len(prices))]\n",
    "        for i in range(1,len(prices)):\n",
    "            diff = prices[i] - prices[i-1]\n",
    "            for j in range(1,k+1):\n",
    "                l[i][j] = max(g[i-1][j-1] + max(0, diff), l[i-1][j] + diff)\n",
    "                g[i][j] = max(l[i][j], g[i-1][j])\n",
    "        return g[-1][-1]\n",
    "    \n",
    "    def maxProfit(self, k, prices):\n",
    "        \"\"\"\n",
    "        :type k: int\n",
    "        :type prices: List[int]\n",
    "        :rtype: int\n",
    "        \"\"\"\n",
    "        if len(prices) < 2:\n",
    "            return 0\n",
    "        # 按照递增序列分段\n",
    "        sums = []\n",
    "        # 跟踪上一个递增序列的最小值\n",
    "        lasti = 0\n",
    "        for i in range(1, len(prices)):\n",
    "            if prices[i] < prices[i-1]:\n",
    "                if prices[i-1] - prices[lasti] > 0:\n",
    "                    sums.append((prices[lasti], prices[i-1]))\n",
    "                # 将递增序列的前端点置为当前节点\n",
    "                lasti = i\n",
    "        # 如果递增直至最后一个元素，需要额外处理\n",
    "        if prices[-1] - prices[lasti] > 0:\n",
    "            sums.append((prices[lasti], prices[-1]))\n",
    "        # print(\"sums\", sums)\n",
    "        # k次交易的profit一定大于k-1次，所以，\n",
    "        # 只需要求k次的即可\n",
    "        if k >= len(sums):\n",
    "            return sum([i[1]-i[0] for i in sums])\n",
    "        else:\n",
    "            np = []\n",
    "            for a, b in sums:\n",
    "                np.append(a)\n",
    "                np.append(b)\n",
    "            return self.dprogramming(k, np)\n",
    "        \"\"\"\n",
    "        window = len(sums) - k\n",
    "        ksums = [i for i in sums]\n",
    "        # 依次递减交易量\n",
    "        while window > 0:\n",
    "            # 缩减到k词交易带来的损失\n",
    "            ksums = self.shrink1trade(ksums)\n",
    "            #sums = [i for i in ksums]\n",
    "            #ksums.clear()\n",
    "            window -= 1\n",
    "        return sum([i[1]-i[0] for i in ksums])\n",
    "        \"\"\"\n",
    "\n",
    "    def shrink1trade(self, profits):\n",
    "        \"\"\"减少一笔交易的最大收益\n",
    "        \n",
    "        减少一笔交易包括剔除一笔或者合并相邻两笔（中间不交易）\n",
    "        \"\"\"\n",
    "        # print(\"\\t======\", profits)\n",
    "        ploss = 10**10\n",
    "        pi = 0\n",
    "        for i in range(len(profits)):\n",
    "            if ploss > profits[i][1] - profits[i][0]:\n",
    "                ploss = profits[i][1] - profits[i][0]\n",
    "                pi = i\n",
    "            if i + 1 < len(profits):\n",
    "                mergeloss = profits[i][1] - profits[i+1][0]\n",
    "                if ploss > mergeloss:\n",
    "                    ploss = mergeloss\n",
    "                    pi = i\n",
    "        np = []\n",
    "        i = 0\n",
    "        while i < len(profits):\n",
    "            if pi == i:\n",
    "                if ploss != profits[i][1] - profits[i][0]:\n",
    "                    # 合并\n",
    "                    np.append((profits[i][0], profits[i+1][1]))\n",
    "                    i += 1\n",
    "                else:\n",
    "                    # 删除，不需要处理\n",
    "                    pass\n",
    "            else:\n",
    "                np.append((profits[i][0], profits[i][1]))\n",
    "            i += 1\n",
    "        return np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def BSTSequences(self, root: TreeNode) -> List[List[int]]:\n",
    "        def merge(arr1, arr2):\n",
    "            if not arr1: return [arr2]\n",
    "            if not arr2: return [arr1]\n",
    "            res = []\n",
    "            nums = merge(arr1[1:], arr2)\n",
    "            for arr in nums:\n",
    "                res.append([arr1[0]]+arr)\n",
    "            nums = merge(arr1, arr2[1:])\n",
    "            for arr in nums:\n",
    "                res.append([arr2[0]]+arr)\n",
    "            return res\n",
    "\n",
    "        if not root: return [[]]\n",
    "        arr1 = self.BSTSequences(root.left)\n",
    "        arr2 = self.BSTSequences(root.right)\n",
    "        l1 = len(arr1[0])\n",
    "        l2 = len(arr2[0])\n",
    "        res = []\n",
    "        if l1 and l2:\n",
    "            for i in arr1:\n",
    "                for j in arr2:\n",
    "                    for arr in merge(i, j):\n",
    "                        res.append([root.val] + arr)\n",
    "        elif l1:\n",
    "            for i in arr1:\n",
    "                res.append([root.val] + i)\n",
    "        elif l2:\n",
    "            for i in arr2:\n",
    "                res.append([root.val] + i)\n",
    "        else:\n",
    "            res = [[root.val]]\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def BSTSequences(self, root: TreeNode) -> List[List[int]]:\n",
    "        if root is None:\n",
    "            return [[]]\n",
    "        left_seqs = self.BSTSequences(root.left) if root.left is not None else [[]]\n",
    "        right_seqs = self.BSTSequences(root.right) if root.right is not None else [[]]\n",
    "        seqs = []\n",
    "        for l in left_seqs:\n",
    "            for r in right_seqs:\n",
    "                seqs.extend(self.merge_sequences(l, 0, r, 0, [root.val]))\n",
    "        return seqs\n",
    "\n",
    "    def merge_sequences(\n",
    "        self,\n",
    "        left: List[int],\n",
    "        left_index: int,\n",
    "        right: List[int],\n",
    "        right_index: int,\n",
    "        temp_seq: List[int],\n",
    "    ) -> List[List[int]]:\n",
    "        if left_index == len(left) and right_index == len(right):\n",
    "            return [temp_seq]\n",
    "        if left_index == len(left):\n",
    "            return [temp_seq + right[right_index:]]\n",
    "        if right_index == len(right):\n",
    "            return [temp_seq + left[left_index:]]\n",
    "        return self.merge_sequences(\n",
    "            left, left_index + 1, right, right_index, temp_seq + [left[left_index]]\n",
    "        ) + self.merge_sequences(\n",
    "            left, left_index, right, right_index + 1, temp_seq + [right[right_index]]\n",
    "        )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "from itertools import product\n",
    "class Solution:\n",
    "    def BSTSequences(self, root: TreeNode) -> List[List[int]]:\n",
    "        res = list()\n",
    "        if root is None:\n",
    "            res.append(list())\n",
    "            return res\n",
    "        left = self.BSTSequences(root.left)\n",
    "        right = self.BSTSequences(root.right)\n",
    "\n",
    "        def merge(i: int, j: int, l: list[int], r: list[int], cur: list[int], m: int, n: int):\n",
    "            if i == m and j == n:\n",
    "                yield cur.copy()\n",
    "            if i < m:\n",
    "                cur.append(l[i])\n",
    "                yield from merge(i + 1, j, l, r, cur, m, n)\n",
    "                cur.pop()\n",
    "            if j < n:\n",
    "                cur.append(r[j])\n",
    "                yield from merge(i, j + 1, l, r, cur, m, n)\n",
    "                cur.pop()\n",
    "        \n",
    "        for l, r in product(left, right):\n",
    "            res.extend(merge(0, 0, l, r, [root.val], len(l), len(r)))\n",
    "        \n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    class DisjointSet:\n",
    "        def __init__(self, n):\n",
    "            self.f = list(range(n))\n",
    "        \n",
    "        def find(self, x):\n",
    "            if x == self.f[x]:\n",
    "                return x\n",
    "            self.f[x] = self.find(self.f[x])\n",
    "            return self.f[x]\n",
    "        \n",
    "        def merge(self, x, y):\n",
    "            self.f[self.find(x)] = self.find(y)\n",
    "    \n",
    "    # 单元格性质建图\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "        m, n = len(grid), len(grid[0])\n",
    "        patterns = [0, 0b1010, 0b0101, 0b1100, 0b0110, 0b1001, 0b0011]\n",
    "        dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n",
    "        ds = Solution.DisjointSet(m * n)\n",
    "        \n",
    "        def getId(x, y):\n",
    "            return x * n + y\n",
    "\n",
    "        def handler(x, y):\n",
    "            pattern = patterns[grid[x][y]]\n",
    "            for i, (dx, dy) in enumerate(dirs):\n",
    "                if (pattern & (1 << i)) > 0:\n",
    "                    sx, sy = x + dx, y + dy\n",
    "                    if 0 <= sx < m and 0 <= sy < n and (patterns[grid[sx][sy]] & (1 << ((i + 2) % 4))) > 0:\n",
    "                        ds.merge(getId(x, y), getId(sx, sy))\n",
    "        \n",
    "        for i in range(m):\n",
    "            for j in range(n):\n",
    "                handler(i, j)\n",
    "        \n",
    "        return ds.find(getId(0, 0)) == ds.find(getId(m - 1, n - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class DisjoinSet:\n",
    "\n",
    "    def __init__(self, n):\n",
    "        self.f = list(range(n))\n",
    "\n",
    "    def find(self, x):\n",
    "        if x == self.f[x]:\n",
    "            return x\n",
    "        self.f[x] = self.find(self.f[x])\n",
    "        return self.f[x]\n",
    "    def merge(self, x, y):\n",
    "        self.f[self.find(x)] = self.find(y)\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "        n, m = len(grid), len(grid[0])\n",
    "        ds = DisjoinSet(n * m)\n",
    "        patterns = [0, 0b1010, 0b0101, 0b1100, 0b0110, 0b1001, 0b0011]\n",
    "        dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n",
    "        \n",
    "        def getId(x, y):\n",
    "            return x * m + y\n",
    "\n",
    "        def handler(x, y):\n",
    "\n",
    "            pattern = patterns[grid[x][y]]\n",
    "\n",
    "            for i, (dx, dy) in enumerate(dirs):\n",
    "                if (pattern & (1 << i)) > 0:\n",
    "                    sx, sy = x + dx, y + dy\n",
    "                    if 0 <= sx < n and 0 <= sy < m and (patterns[grid[sx][sy]] & (1 << (i + 2) % 4)) > 0:\n",
    "                        ds.merge(getId(x, y), getId(sx, sy))\n",
    "        \n",
    "\n",
    "        for i in range(n):\n",
    "            for j in range(m):\n",
    "\n",
    "                handler(i , j)\n",
    "        \n",
    "        return ds.find(getId(0, 0)) == ds.find(getId(n - 1, m - 1))\n",
    "        # n, m = len(grid), len(grid[0])\n",
    "        # ds = DisjoinSet(n * m)\n",
    "\n",
    "        # def getId(x, y):\n",
    "        #     return x * m + y\n",
    "\n",
    "        # def detectL(x, y):\n",
    "        #     if 0 <= x < n and 0 <= y - 1 < m and grid[x][y - 1] in set([1, 4, 6]):\n",
    "        #         ds.merge(getId(x, y), getId(x, y - 1))\n",
    "        # def detectR(x, y):\n",
    "        #     if 0 <= x < n and 0 <= y + 1 < m and grid[x][y + 1] in set([1, 3, 5]):\n",
    "        #         ds.merge(getId(x, y), getId(x, y + 1))\n",
    "\n",
    "        # def detectU(x, y):\n",
    "        #     if 0 <= x - 1 < n and 0 <= y < m and grid[x - 1][y] in set([2, 3, 4]):\n",
    "        #         ds.merge(getId(x, y), getId(x - 1, y ))\n",
    "\n",
    "        # def detectD(x, y):\n",
    "        #     if 0 <= x + 1 < n and 0 <= y < m and grid[x + 1][y] in set([2, 5, 6]):\n",
    "        #         ds.merge(getId(x, y), getId(x + 1, y ))\n",
    "\n",
    "        # def handler(x, y):\n",
    "        #     if grid[x][y] == 1:\n",
    "        #         detectL(x, y)\n",
    "        #         detectR(x, y)\n",
    "        #     elif grid[x][y] == 2:\n",
    "        #         detectU(x, y)\n",
    "        #         detectD(x, y)\n",
    "        #     elif grid[x][y] == 3:\n",
    "        #         detectL(x, y)\n",
    "        #         detectD(x, y)\n",
    "        #     elif grid[x][y] == 4:\n",
    "        #         detectR(x, y)\n",
    "        #         detectD(x, y)\n",
    "        #     elif grid[x][y] == 5:\n",
    "        #         detectL(x, y)\n",
    "        #         detectU(x, y)\n",
    "        #     else:\n",
    "        #         detectR(x, y)\n",
    "        #         detectU(x, y)\n",
    "\n",
    "        # for i in range(n):\n",
    "        #     for j in range(m):\n",
    "\n",
    "        #         handler(i , j)\n",
    "\n",
    "        \n",
    "        # return ds.find(getId(0, 0)) == ds.find(getId(n - 1, m - 1))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class DisjoinSet:\n",
    "\n",
    "    def __init__(self, n):\n",
    "        self.f = list(range(n))\n",
    "\n",
    "    def find(self, x):\n",
    "        if x == self.f[x]:\n",
    "            return x\n",
    "        self.f[x] = self.find(self.f[x])\n",
    "        return self.f[x]\n",
    "    def merge(self, x, y):\n",
    "        self.f[self.find(x)] = self.find(y)\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "\n",
    "        n, m = len(grid), len(grid[0])\n",
    "        ds = DisjoinSet(n * m)\n",
    "        patterns = [0, 0b1010, 0b0101, 0b1100, 0b0110, 0b1001, 0b0011]\n",
    "        dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n",
    "        \n",
    "        def getId(x, y):\n",
    "            return x * m + y\n",
    "\n",
    "        def handler(x, y):\n",
    "\n",
    "            pattern = patterns[grid[x][y]]\n",
    "\n",
    "            for i, (dx, dy) in enumerate(dirs):\n",
    "                if (pattern & (1 << i)) > 0:\n",
    "                    sx, sy = x + dx, y + dy\n",
    "                    if 0 <= sx < n and 0 <= sy < m and (patterns[grid[sx][sy]] & (1 << (i + 2) % 4)) > 0:\n",
    "                        ds.merge(getId(x, y), getId(sx, sy))\n",
    "        \n",
    "\n",
    "        for i in range(n):\n",
    "            for j in range(m):\n",
    "\n",
    "                handler(i , j)\n",
    "        \n",
    "        return ds.find(getId(0, 0)) == ds.find(getId(n - 1, m - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    class DisjointSet:\n",
    "        def __init__(self, n):\n",
    "            self.f = list(range(n))\n",
    "        \n",
    "        def find(self, x):\n",
    "            if x == self.f[x]:\n",
    "                return x\n",
    "            self.f[x] = self.find(self.f[x])\n",
    "            return self.f[x]\n",
    "        \n",
    "        def merge(self, x, y):\n",
    "            self.f[self.find(x)] = self.find(y)\n",
    "\n",
    "    # 邻接关系建图\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "        m, n = len(grid), len(grid[0])\n",
    "        ds = Solution.DisjointSet(m * n)\n",
    "\n",
    "        def getId(x, y):\n",
    "            return x * n + y\n",
    "        \n",
    "        def detectL(x, y):\n",
    "            if y - 1 >= 0 and grid[x][y - 1] in [1, 4, 6]:\n",
    "                ds.merge(getId(x, y), getId(x, y - 1))\n",
    "        \n",
    "        def detectR(x, y):\n",
    "            if y + 1 < n and grid[x][y + 1] in [1, 3, 5]:\n",
    "                ds.merge(getId(x, y), getId(x, y + 1))\n",
    "        \n",
    "        def detectU(x, y):\n",
    "            if x - 1 >= 0 and grid[x - 1][y] in [2, 3, 4]:\n",
    "                ds.merge(getId(x, y), getId(x - 1, y))\n",
    "        \n",
    "        def detectD(x, y):\n",
    "            if x + 1 < m and grid[x + 1][y] in [2, 5, 6]:\n",
    "                ds.merge(getId(x, y), getId(x + 1, y))\n",
    "\n",
    "        def handler(x, y):\n",
    "            if grid[x][y] == 1:\n",
    "                detectL(x, y)\n",
    "                detectR(x, y)\n",
    "            elif grid[x][y] == 2:\n",
    "                detectU(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 3:\n",
    "                detectL(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 4:\n",
    "                detectR(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 5:\n",
    "                detectL(x, y)\n",
    "                detectU(x, y)\n",
    "            else:\n",
    "                detectR(x, y)\n",
    "                detectU(x, y)\n",
    "        \n",
    "        for i in range(m):\n",
    "            for j in range(n):\n",
    "                handler(i, j)\n",
    "        \n",
    "        return ds.find(getId(0, 0)) == ds.find(getId(m - 1, n - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    class DisjoinSet():\n",
    "        def __init__(self, n):\n",
    "            self.f = list(range(n))\n",
    "\n",
    "        def find(self, x):\n",
    "            if x == self.f[x]:\n",
    "                return x\n",
    "            self.f[x] = self.find(self.f[x])\n",
    "            return self.f[x]\n",
    "\n",
    "        def merge(self, x, y):\n",
    "            self.f[self.find(x)] = self.find(y)\n",
    "\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "        m = len(grid)\n",
    "        n = len(grid[0])\n",
    "        ds = Solution.DisjoinSet(m*n)\n",
    "        \n",
    "        def getId(x, y):\n",
    "            return x * n + y\n",
    "        \n",
    "        def detectL(x, y):\n",
    "            if y - 1 >= 0 and grid[x][y - 1] in [1, 4, 6]:\n",
    "                ds.merge(getId(x, y), getId(x, y - 1))\n",
    "        \n",
    "        def detectR(x, y):\n",
    "            if y + 1 < n and grid[x][y + 1] in [1, 3, 5]:\n",
    "                ds.merge(getId(x, y), getId(x, y + 1))\n",
    "        \n",
    "        def detectU(x, y):\n",
    "            if x - 1 >= 0 and grid[x - 1][y] in [2, 3, 4]:\n",
    "                ds.merge(getId(x, y), getId(x - 1, y))\n",
    "        \n",
    "        def detectD(x, y):\n",
    "            if x + 1 < m and grid[x + 1][y] in [2, 5, 6]:\n",
    "                ds.merge(getId(x, y), getId(x + 1, y))\n",
    "\n",
    "        def handler(x, y):\n",
    "            if grid[x][y] == 1:\n",
    "                detectL(x, y)\n",
    "                detectR(x, y)\n",
    "            elif grid[x][y] == 2:\n",
    "                detectU(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 3:\n",
    "                detectL(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 4:\n",
    "                detectR(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 5:\n",
    "                detectL(x, y)\n",
    "                detectU(x, y)\n",
    "            else:\n",
    "                detectR(x, y)\n",
    "                detectU(x, y)\n",
    "        for j in range(n):\n",
    "            for i in range(m):\n",
    "                handler(i, j)\n",
    "        \n",
    "        return ds.find(getId(0, 0)) == ds.find(getId(m - 1, n - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    class DisjointSet:\n",
    "        def __init__(self, n):\n",
    "            self.f = list(range(n))\n",
    "        \n",
    "        def find(self, x):\n",
    "            if x == self.f[x]:\n",
    "                return x\n",
    "            self.f[x] = self.find(self.f[x])\n",
    "            return self.f[x]\n",
    "        \n",
    "        def merge(self, x, y):\n",
    "            self.f[self.find(x)] = self.find(y)\n",
    "\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "        m, n = len(grid), len(grid[0])\n",
    "        ds = Solution.DisjointSet(m * n)\n",
    "\n",
    "        def getId(x, y):\n",
    "            return x * n + y\n",
    "        \n",
    "        def detectL(x, y):\n",
    "            if y - 1 >= 0 and grid[x][y - 1] in [1, 4, 6]:\n",
    "                ds.merge(getId(x, y), getId(x, y - 1))\n",
    "        \n",
    "        def detectR(x, y):\n",
    "            if y + 1 < n and grid[x][y + 1] in [1, 3, 5]:\n",
    "                ds.merge(getId(x, y), getId(x, y + 1))\n",
    "        \n",
    "        def detectU(x, y):\n",
    "            if x - 1 >= 0 and grid[x - 1][y] in [2, 3, 4]:\n",
    "                ds.merge(getId(x, y), getId(x - 1, y))\n",
    "        \n",
    "        def detectD(x, y):\n",
    "            if x + 1 < m and grid[x + 1][y] in [2, 5, 6]:\n",
    "                ds.merge(getId(x, y), getId(x + 1, y))\n",
    "\n",
    "        def handler(x, y):\n",
    "            if grid[x][y] == 1:\n",
    "                detectL(x, y)\n",
    "                detectR(x, y)\n",
    "            elif grid[x][y] == 2:\n",
    "                detectU(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 3:\n",
    "                detectL(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 4:\n",
    "                detectR(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 5:\n",
    "                detectL(x, y)\n",
    "                detectU(x, y)\n",
    "            else:\n",
    "                detectR(x, y)\n",
    "                detectU(x, y)\n",
    "        \n",
    "        for i in range(m):\n",
    "            for j in range(n):\n",
    "                handler(i, j)\n",
    "        \n",
    "        return ds.find(getId(0, 0)) == ds.find(getId(m - 1, n - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    class DisjointSet:\n",
    "        def __init__(self, n):\n",
    "            self.f = list(range(n))\n",
    "        \n",
    "        def find(self, x):\n",
    "            if x == self.f[x]:\n",
    "                return x\n",
    "            self.f[x] = self.find(self.f[x])\n",
    "            return self.f[x]\n",
    "        \n",
    "        def merge(self, x, y):\n",
    "            self.f[self.find(x)] = self.find(y)\n",
    "\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "        m, n = len(grid), len(grid[0])\n",
    "        ds = Solution.DisjointSet(m * n)\n",
    "\n",
    "        def getId(x, y):\n",
    "            return x * n + y\n",
    "        \n",
    "        def detectL(x, y):\n",
    "            if y - 1 >= 0 and grid[x][y - 1] in [1, 4, 6]:\n",
    "                ds.merge(getId(x, y), getId(x, y - 1))\n",
    "        \n",
    "        def detectR(x, y):\n",
    "            if y + 1 < n and grid[x][y + 1] in [1, 3, 5]:\n",
    "                ds.merge(getId(x, y), getId(x, y + 1))\n",
    "        \n",
    "        def detectU(x, y):\n",
    "            if x - 1 >= 0 and grid[x - 1][y] in [2, 3, 4]:\n",
    "                ds.merge(getId(x, y), getId(x - 1, y))\n",
    "        \n",
    "        def detectD(x, y):\n",
    "            if x + 1 < m and grid[x + 1][y] in [2, 5, 6]:\n",
    "                ds.merge(getId(x, y), getId(x + 1, y))\n",
    "\n",
    "        def handler(x, y):\n",
    "            if grid[x][y] == 1:\n",
    "                detectL(x, y)\n",
    "                detectR(x, y)\n",
    "            elif grid[x][y] == 2:\n",
    "                detectU(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 3:\n",
    "                detectL(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 4:\n",
    "                detectR(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 5:\n",
    "                detectL(x, y)\n",
    "                detectU(x, y)\n",
    "            else:\n",
    "                detectR(x, y)\n",
    "                detectU(x, y)\n",
    "        \n",
    "        for i in range(m):\n",
    "            for j in range(n):\n",
    "                handler(i, j)\n",
    "        \n",
    "        return ds.find(getId(0, 0)) == ds.find(getId(m - 1, n - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    class DisjointSet:\n",
    "        def __init__(self, n):\n",
    "            self.f = list(range(n))\n",
    "        \n",
    "        def find(self, x):\n",
    "            if x == self.f[x]:\n",
    "                return x\n",
    "            self.f[x] = self.find(self.f[x])\n",
    "            return self.f[x]\n",
    "        \n",
    "        def merge(self, x, y):\n",
    "            self.f[self.find(x)] = self.find(y)\n",
    "\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "        m, n = len(grid), len(grid[0])\n",
    "        ds = Solution.DisjointSet(m * n)\n",
    "\n",
    "        def getId(x, y):\n",
    "            return x * n + y\n",
    "        \n",
    "        def detectL(x, y):\n",
    "            if y - 1 >= 0 and grid[x][y - 1] in [1, 4, 6]:\n",
    "                ds.merge(getId(x, y), getId(x, y - 1))\n",
    "        \n",
    "        def detectR(x, y):\n",
    "            if y + 1 < n and grid[x][y + 1] in [1, 3, 5]:\n",
    "                ds.merge(getId(x, y), getId(x, y + 1))\n",
    "        \n",
    "        def detectU(x, y):\n",
    "            if x - 1 >= 0 and grid[x - 1][y] in [2, 3, 4]:\n",
    "                ds.merge(getId(x, y), getId(x - 1, y))\n",
    "        \n",
    "        def detectD(x, y):\n",
    "            if x + 1 < m and grid[x + 1][y] in [2, 5, 6]:\n",
    "                ds.merge(getId(x, y), getId(x + 1, y))\n",
    "\n",
    "        def handler(x, y):\n",
    "            if grid[x][y] == 1:\n",
    "                detectL(x, y)\n",
    "                detectR(x, y)\n",
    "            elif grid[x][y] == 2:\n",
    "                detectU(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 3:\n",
    "                detectL(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 4:\n",
    "                detectR(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 5:\n",
    "                detectL(x, y)\n",
    "                detectU(x, y)\n",
    "            else:\n",
    "                detectR(x, y)\n",
    "                detectU(x, y)\n",
    "        \n",
    "        for i in range(m):\n",
    "            for j in range(n):\n",
    "                handler(i, j)\n",
    "        \n",
    "        return ds.find(getId(0, 0)) == ds.find(getId(m - 1, n - 1))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class DisjoinSet:\n",
    "\n",
    "    def __init__(self, n):\n",
    "        self.f = list(range(n))\n",
    "\n",
    "    def find(self, x):\n",
    "        if x == self.f[x]:\n",
    "            return x\n",
    "        self.f[x] = self.find(self.f[x])\n",
    "        return self.f[x]\n",
    "    def merge(self, x, y):\n",
    "        self.f[self.find(x)] = self.find(y)\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "\n",
    "        n, m = len(grid), len(grid[0])\n",
    "        ds = DisjoinSet(n * m)\n",
    "\n",
    "        def getId(x, y):\n",
    "            return x * m + y\n",
    "\n",
    "        def detectL(x, y):\n",
    "            if 0 <= x < n and 0 <= y - 1 < m and grid[x][y - 1] in set([1, 4, 6]):\n",
    "                ds.merge(getId(x, y), getId(x, y - 1))\n",
    "        def detectR(x, y):\n",
    "            if 0 <= x < n and 0 <= y + 1 < m and grid[x][y + 1] in set([1, 3, 5]):\n",
    "                ds.merge(getId(x, y), getId(x, y + 1))\n",
    "\n",
    "        def detectU(x, y):\n",
    "            if 0 <= x - 1 < n and 0 <= y < m and grid[x - 1][y] in set([2, 3, 4]):\n",
    "                ds.merge(getId(x, y), getId(x - 1, y ))\n",
    "\n",
    "        def detectD(x, y):\n",
    "            if 0 <= x + 1 < n and 0 <= y < m and grid[x + 1][y] in set([2, 5, 6]):\n",
    "                ds.merge(getId(x, y), getId(x + 1, y ))\n",
    "\n",
    "        def handler(x, y):\n",
    "            if grid[x][y] == 1:\n",
    "                detectL(x, y)\n",
    "                detectR(x, y)\n",
    "            elif grid[x][y] == 2:\n",
    "                detectU(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 3:\n",
    "                detectL(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 4:\n",
    "                detectR(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 5:\n",
    "                detectL(x, y)\n",
    "                detectU(x, y)\n",
    "            else:\n",
    "                detectR(x, y)\n",
    "                detectU(x, y)\n",
    "\n",
    "        for i in range(n):\n",
    "            for j in range(m):\n",
    "\n",
    "                handler(i , j)\n",
    "\n",
    "        \n",
    "        return ds.find(getId(0, 0)) == ds.find(getId(n - 1, m - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class DisjoinSet:\n",
    "\n",
    "    def __init__(self, n):\n",
    "        self.f = list(range(n))\n",
    "\n",
    "    def find(self, x):\n",
    "        if x == self.f[x]:\n",
    "            return x\n",
    "        self.f[x] = self.find(self.f[x])\n",
    "        return self.f[x]\n",
    "    def merge(self, x, y):\n",
    "        self.f[self.find(x)] = self.find(y)\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "\n",
    "        n, m = len(grid), len(grid[0])\n",
    "        ds = DisjoinSet(n * m)\n",
    "\n",
    "        def getId(x, y):\n",
    "            return x * m + y\n",
    "\n",
    "        def detectL(x, y):\n",
    "            if 0 <= x < n and 0 <= y - 1 < m and grid[x][y - 1] in set([1, 4, 6]):\n",
    "                ds.merge(getId(x, y), getId(x, y - 1))\n",
    "        def detectR(x, y):\n",
    "            if 0 <= x < n and 0 <= y + 1 < m and grid[x][y + 1] in set([1, 3, 5]):\n",
    "                ds.merge(getId(x, y), getId(x, y + 1))\n",
    "\n",
    "        def detectU(x, y):\n",
    "            if 0 <= x - 1 < n and 0 <= y < m and grid[x - 1][y] in set([2, 3, 4]):\n",
    "                ds.merge(getId(x, y), getId(x - 1, y ))\n",
    "\n",
    "        def detectD(x, y):\n",
    "            if 0 <= x + 1 < n and 0 <= y < m and grid[x + 1][y] in set([2, 5, 6]):\n",
    "                ds.merge(getId(x, y), getId(x + 1, y ))\n",
    "\n",
    "        def handler(x, y):\n",
    "            if grid[x][y] == 1:\n",
    "                detectL(x, y)\n",
    "                detectR(x, y)\n",
    "            elif grid[x][y] == 2:\n",
    "                detectU(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 3:\n",
    "                detectL(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 4:\n",
    "                detectR(x, y)\n",
    "                detectD(x, y)\n",
    "            elif grid[x][y] == 5:\n",
    "                detectL(x, y)\n",
    "                detectU(x, y)\n",
    "            else:\n",
    "                detectR(x, y)\n",
    "                detectU(x, y)\n",
    "\n",
    "        for i in range(n):\n",
    "            for j in range(m):\n",
    "\n",
    "                handler(i , j)\n",
    "\n",
    "        \n",
    "        return ds.find(getId(0, 0)) == ds.find(getId(n - 1, m - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "        # 题意是什么意思，给你一张图，让你判断图中（0，0）到（m-1,n-1）是否连通\n",
    "        # 1：1，3，5     2：2，5，6        3：2，5，6      4：2，5，6      5，1，6\n",
    "        # 并查集\n",
    "        m = len(grid)\n",
    "        n = len(grid[0])\n",
    "        fa = list(range(m*n))\n",
    "        def find(x):\n",
    "            if x == fa[x]:\n",
    "                return x\n",
    "            fa[x] = find(fa[x])\n",
    "            return fa[x]\n",
    "        def merge(x,y):\n",
    "            fa[find(x)] = find(y)\n",
    "        # 连通\n",
    "        def getId(x,y):\n",
    "            return x*n+y\n",
    "        def detectL(x,y):\n",
    "            if y-1>= 0 and grid[x][y-1] in [1,4,6]:\n",
    "                merge(getId(x,y),getId(x,y-1))\n",
    "        def detectR(x,y):\n",
    "            if y+1 < n and grid[x][y+1] in [1,3,5]:\n",
    "                merge(getId(x,y),getId(x,y+1))\n",
    "        def detectU(x,y):\n",
    "            if x-1>= 0 and grid[x-1][y] in [2,4,3]:\n",
    "                merge(getId(x,y),getId(x-1,y))\n",
    "        def detectD(x,y):\n",
    "            if x+1 < m and grid[x+1][y] in [2,5,6]:\n",
    "                merge(getId(x,y),getId(x+1,y))\n",
    "        def handler(x,y):\n",
    "            if grid[x][y] == 1:\n",
    "                detectL(x,y)\n",
    "                detectR(x,y)\n",
    "            if grid[x][y] == 2:\n",
    "                detectU(x,y)\n",
    "                detectD(x,y)\n",
    "            if grid[x][y] == 3:\n",
    "                detectL(x,y)\n",
    "                detectD(x,y)\n",
    "            if grid[x][y] == 4:\n",
    "                detectD(x,y)\n",
    "                detectR(x,y)\n",
    "            if grid[x][y] == 5:\n",
    "                detectU(x,y)\n",
    "                detectL(x,y)\n",
    "            if grid[x][y] == 6:\n",
    "                detectU(x,y)\n",
    "                detectR(x,y)\n",
    "        for i in range(m):\n",
    "            for j in range(n):\n",
    "                handler(i,j)\n",
    "        return find(getId(0,0)) == find(getId(m-1,n-1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "        # 题意是什么意思，给你一张图，让你判断图中（0，0）到（m-1,n-1）是否连通\n",
    "        # 1：1，3，5     2：2，5，6        3：2，5，6      4：2，5，6      5，1，6\n",
    "        # 并查集\n",
    "        m = len(grid)\n",
    "        n = len(grid[0])\n",
    "        fa = list(range(m*n))\n",
    "        def find(x):\n",
    "        # 找x的根节点\n",
    "            if x != fa[x]:\n",
    "                fa[x] = find(fa[x])\n",
    "            return fa[x]\n",
    "        def merge(x,y):\n",
    "            fa[find(x)] = find(y)\n",
    "        # 连通\n",
    "        def getId(x,y):\n",
    "            return x*n+y\n",
    "        def detectL(x,y):\n",
    "            if y-1>= 0 and grid[x][y-1] in [1,4,6]:\n",
    "                merge(getId(x,y),getId(x,y-1))\n",
    "        def detectR(x,y):\n",
    "            if y+1 < n and grid[x][y+1] in [1,3,5]:\n",
    "                merge(getId(x,y),getId(x,y+1))\n",
    "        def detectU(x,y):\n",
    "            if x-1>= 0 and grid[x-1][y] in [2,4,3]:\n",
    "                merge(getId(x,y),getId(x-1,y))\n",
    "        def detectD(x,y):\n",
    "            if x+1 < m and grid[x+1][y] in [2,5,6]:\n",
    "                merge(getId(x,y),getId(x+1,y))\n",
    "        def handler(x,y):\n",
    "            if grid[x][y] == 1:\n",
    "                detectL(x,y)\n",
    "                detectR(x,y)\n",
    "            if grid[x][y] == 2:\n",
    "                detectU(x,y)\n",
    "                detectD(x,y)\n",
    "            if grid[x][y] == 3:\n",
    "                detectL(x,y)\n",
    "                detectD(x,y)\n",
    "            if grid[x][y] == 4:\n",
    "                detectD(x,y)\n",
    "                detectR(x,y)\n",
    "            if grid[x][y] == 5:\n",
    "                detectU(x,y)\n",
    "                detectL(x,y)\n",
    "            if grid[x][y] == 6:\n",
    "                detectU(x,y)\n",
    "                detectR(x,y)\n",
    "        for i in range(m):\n",
    "            for j in range(n):\n",
    "                handler(i,j)\n",
    "        return find(getId(0,0)) == find(getId(m-1,n-1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def hasValidPath(self, grid: List[List[int]]) -> bool:\n",
    "        m,n = len(grid),len(grid[0])\n",
    "        fa = list(range(m*n))\n",
    "        # 并查集\n",
    "        def find(x):\n",
    "            if fa[x] != x:\n",
    "                fa[x] = find(fa[x])\n",
    "            return fa[x]\n",
    "        def merge(x,y):\n",
    "            fa[find(x)] = find(y)\n",
    "        def get_id(x,y):\n",
    "            return x*n+y\n",
    "        # 连通\n",
    "        def link_l(x,y):\n",
    "            if 0 <= y-1 and grid[x][y-1] in [1,4,6]:\n",
    "                merge(get_id(x,y),get_id(x,y-1))\n",
    "        def link_r(x,y):\n",
    "            if y+1<n and grid[x][y+1] in [1,3,5]:\n",
    "                merge(get_id(x,y),get_id(x,y+1))\n",
    "        def link_u(x,y):\n",
    "            if 0 <= x-1 and grid[x-1][y] in [2,3,4]:\n",
    "                merge(get_id(x,y),get_id(x-1,y))\n",
    "        def link_d(x,y):\n",
    "            if x+1<m and grid[x+1][y] in [2,5,6]:\n",
    "                merge(get_id(x,y),get_id(x+1,y))\n",
    "        def link(x,y):\n",
    "            if grid[x][y] == 1:\n",
    "                link_l(x,y)\n",
    "                link_r(x,y)\n",
    "            if grid[x][y] == 2:\n",
    "                link_u(x,y)\n",
    "                link_d(x,y)\n",
    "            if grid[x][y] == 3:\n",
    "                link_l(x,y)\n",
    "                link_d(x,y)\n",
    "            if grid[x][y] == 4:\n",
    "                link_d(x,y)\n",
    "                link_r(x,y)\n",
    "            if grid[x][y] == 5:\n",
    "                link_l(x,y)\n",
    "                link_u(x,y)\n",
    "            if grid[x][y] == 6:\n",
    "                link_u(x,y)\n",
    "                link_r(x,y)\n",
    "        for i in range(m):\n",
    "            for j in range(n):\n",
    "                link(i,j)\n",
    "        return find(get_id(0,0)) == find(get_id(m-1,n-1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n",
    "        edgeList.sort(key=lambda e: e[2])\n",
    "\n",
    "        # 并查集模板\n",
    "        fa = list(range(n))\n",
    "        def find(x: int) -> int:\n",
    "            if fa[x] != x:\n",
    "                fa[x] = find(fa[x])\n",
    "            return fa[x]\n",
    "        def merge(from_: int, to: int) -> None:\n",
    "            fa[find(from_)] = find(to)\n",
    "\n",
    "        ans, k = [False] * len(queries), 0\n",
    "        # 查询的下标按照 limit 从小到大排序，方便离线\n",
    "        for i, (p, q, limit) in sorted(enumerate(queries), key=lambda p: p[1][2]):\n",
    "            while k < len(edgeList) and edgeList[k][2] < limit:\n",
    "                merge(edgeList[k][0], edgeList[k][1])\n",
    "                k += 1\n",
    "            ans[i] = find(p) == find(q)\n",
    "        return ans\n",
    "\n",
    "# 作者：力扣官方题解\n",
    "# 链接：https://leetcode.cn/problems/checking-existence-of-edge-length-limited-paths/solutions/2018397/jian-cha-bian-chang-du-xian-zhi-de-lu-ji-cdr5/\n",
    "# 来源：力扣（LeetCode）\n",
    "# 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from typing import List\n",
    "\n",
    "class UnionFind:\n",
    "    def __init__(self, n):\n",
    "        self.parent = list(range(n))\n",
    "        \n",
    "    def find(self, u):\n",
    "        if self.parent[u] == u:\n",
    "            return u\n",
    "        self.parent[u] = self.find(self.parent[u])\n",
    "        return self.parent[u]\n",
    "    \n",
    "    def merge(self, u, v):\n",
    "        u = self.find(u)\n",
    "        v = self.find(v)\n",
    "        if u == v:\n",
    "            return\n",
    "        self.parent[u] = v\n",
    "        \n",
    "class Solution:\n",
    "    def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n",
    "        edgeList.sort(key=lambda x: x[2])\n",
    "        queries = sorted(enumerate(queries), key=lambda x: x[1][2])\n",
    "        \n",
    "        uf = UnionFind(n)\n",
    "        answer = [False] * len(queries)\n",
    "        edge_idx = 0\n",
    "        \n",
    "        for i, (p, q, limit) in queries:\n",
    "            while edge_idx < len(edgeList) and edgeList[edge_idx][2] < limit:\n",
    "                uf.merge(edgeList[edge_idx][0], edgeList[edge_idx][1])\n",
    "                edge_idx += 1\n",
    "            \n",
    "            answer[i] = (uf.find(p) == uf.find(q))\n",
    "        \n",
    "        return answer\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "\n",
    "def merge(r1, r2, target, k):\n",
    "    tmp = [(abs(n - target), n) for n in r1 + r2]\n",
    "    tmp.sort()\n",
    "    return [n[1] for n in tmp[:k]]\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def closestKValues(self, root: Optional[TreeNode], target: float, k: int) -> List[int]:\n",
    "        results = []\n",
    "        def dfs(root):\n",
    "            if not root:\n",
    "                return \n",
    "\n",
    "            dfs(root.left)\n",
    "            dfs(root.right)\n",
    "            \n",
    "            item = (-abs(root.val - target), root.val)\n",
    "            if len(results) < k:\n",
    "                heapq.heappush(results, item)\n",
    "            else:\n",
    "                heapq.heappushpop(results, item)\n",
    "        dfs(root)\n",
    "        return [r[1] for r in results]\n",
    "        \n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def largestNumber(self, cost: List[int], target: int) -> str:\n",
    "        dp=['0']*(target+1)\n",
    "        cost_map={c:i+1 for i,c in enumerate(cost)}\n",
    "        #print('cost',cost_map)\n",
    "        def merge(s,bit):\n",
    "            if s=='0':\n",
    "                return '0'\n",
    "            for i in range(len(s)):\n",
    "                ch=s[i]\n",
    "                if int(ch)<=bit:\n",
    "                    return s[:i]+str(bit)+s[i:]\n",
    "            return s+str(bit)\n",
    "        for i in range(1,target+1):\n",
    "            for c,bit in cost_map.items():\n",
    "                tmp=''\n",
    "                if i-c==0:\n",
    "                    tmp=str(bit)\n",
    "                elif i-c>0:\n",
    "                    tmp=merge(dp[i-c],bit)\n",
    "                if len(tmp)>len(dp[i]):\n",
    "                    dp[i]=tmp\n",
    "                elif len(tmp)==len(dp[i]):\n",
    "                    buf=[tmp,dp[i]]\n",
    "                    buf.sort()\n",
    "                    dp[i]=buf[1]\n",
    "        return dp[-1]\n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def largestNumber(self, cost: List[int], target: int) -> str:\n",
    "        dp=['0']*(target+1)\n",
    "        cost_map={c:i+1 for i,c in enumerate(cost)}\n",
    "        def merge(s,bit):\n",
    "            if s=='0':\n",
    "                return '0'\n",
    "            for i in range(len(s)):\n",
    "                ch=s[i]\n",
    "                if int(ch)<=bit:\n",
    "                    return s[:i]+str(bit)+s[i:]\n",
    "            return s+str(bit)\n",
    "        for i in range(1,target+1):\n",
    "            for c,bit in cost_map.items():\n",
    "                tmp=''\n",
    "                if i-c==0:\n",
    "                    tmp=str(bit)\n",
    "                elif i-c>0:\n",
    "                    tmp=merge(dp[i-c],bit)\n",
    "                if len(tmp)>len(dp[i]):\n",
    "                    dp[i]=tmp\n",
    "                elif len(tmp)==len(dp[i]):\n",
    "                    buf=[tmp,dp[i]]\n",
    "                    buf.sort()\n",
    "                    dp[i]=buf[1]\n",
    "        return dp[-1]\n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class UnionFind:\n",
    "    def __init__(self, n) -> None:\n",
    "        self.components = n\n",
    "        self.fa = list(range(n))\n",
    "        self.rank = [1] * n\n",
    "\n",
    "    def __str__(self) -> str:\n",
    "        return \" \".join(map(str, self.fa))\n",
    "\n",
    "    def find(self, x):\n",
    "        if self.fa[x] != x:\n",
    "            self.fa[x] = self.find(self.fa[x])\n",
    "        return self.fa[x]\n",
    "\n",
    "    def union(self, x, y):\n",
    "        fx, fy = self.find(x), self.find(y)\n",
    "        if fx == fy:\n",
    "            return False\n",
    "        if self.rank[fy] > self.rank[fx]:\n",
    "            fx, fy = fy, fx\n",
    "        self.fa[fy] = fx\n",
    "        self.rank[fx] += self.rank[fy]\n",
    "        self.components -= 1\n",
    "        return True\n",
    "\n",
    "    def is_connected(self, x, y):\n",
    "        return self.find(x) == self.find(y)\n",
    "\n",
    "    def all_is_connected(self):\n",
    "        return self.components == 1\n",
    "\n",
    "    def size(self, x):\n",
    "        return self.rank[self.find(x)]\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def gcdSort(self, nums: List[int]) -> bool:\n",
    "        N = max(nums) + 1\n",
    "        uf = UnionFind(N)\n",
    "\n",
    "        for x in nums:\n",
    "            i = 2\n",
    "            y = x\n",
    "            # merge x to it's primes\n",
    "            while i * i <= x:\n",
    "                if x % i == 0:\n",
    "                    uf.union(y, i)\n",
    "                    while x % i == 0:\n",
    "                        x //= i\n",
    "                i += 1\n",
    "            if x > 1:\n",
    "                uf.union(y, x)\n",
    "\n",
    "        for x, y in zip(nums, sorted(nums)):\n",
    "            # print(x, y, uf)\n",
    "            if not uf.is_connected(x, y):\n",
    "                return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\r\n",
    "# class TreeNode:\r\n",
    "#     def __init__(self, val=0, left=None, right=None):\r\n",
    "#         self.val = val\r\n",
    "#         self.left = left\r\n",
    "#         self.right = right\r\n",
    "def checkBST(root: TreeNode) -> tuple[bool, int, int]:\r\n",
    "    if root.left is None and root.right is None:\r\n",
    "        return True, root.val, root.val\r\n",
    "    if root.left is None:\r\n",
    "        rightBST, rightMin, rightMax = checkBST(root.right)\r\n",
    "        return rightBST and root.val < rightMin, root.val, rightMax\r\n",
    "    if root.right is None:\r\n",
    "        leftBST, leftMin, leftMax = checkBST(root.left)\r\n",
    "        return leftBST and root.val > leftMax, leftMin, root.val\r\n",
    "\r\n",
    "    leftBST, leftMin, leftMax = checkBST(root.left)\r\n",
    "    rightBST, rightMin, rightMax = checkBST(root.right)\r\n",
    "    return leftBST and rightBST and leftMax < root.val < rightMin, leftMin, rightMax\r\n",
    "\r\n",
    "class Solution:\r\n",
    "    def canMerge(self, trees: List[TreeNode]) -> Optional[TreeNode]:\r\n",
    "        # find leaves\r\n",
    "        m = 50001\r\n",
    "        n = 0\r\n",
    "        leaves: dict[int, tuple[int, int]] = dict()\r\n",
    "        for i, node in enumerate(trees):\r\n",
    "            _, l, r = checkBST(node)\r\n",
    "            m = min(m, l)\r\n",
    "            n = max(n, r)\r\n",
    "            # node with no children is not considered as leaf\r\n",
    "            # because no roots having same val, therefore no other tree can merge to it\r\n",
    "            if node.left is not None:\r\n",
    "                if node.left.val in leaves:\r\n",
    "                    return None\r\n",
    "                leaves[node.left.val] = (i, 0)\r\n",
    "            if node.right is not None:\r\n",
    "                if node.right.val in leaves:\r\n",
    "                    return None\r\n",
    "                leaves[node.right.val] = (i, 1)\r\n",
    "        \r\n",
    "        # find root\r\n",
    "        root = None\r\n",
    "        for node in trees:\r\n",
    "            # all roots needs to match with one leaf, except one as final root\r\n",
    "            if node.val not in leaves:\r\n",
    "                if root is not None:\r\n",
    "                    return None\r\n",
    "                root = node\r\n",
    "        \r\n",
    "        if root is None:\r\n",
    "            root = trees[0]\r\n",
    "\r\n",
    "        # build tree\r\n",
    "        for node in trees:\r\n",
    "            if node is not root:\r\n",
    "                if leaves[node.val][1] == 0:\r\n",
    "                    trees[leaves[node.val][0]].left = node\r\n",
    "                else:\r\n",
    "                    trees[leaves[node.val][0]].right = node\r\n",
    "\r\n",
    "        b, l, r = checkBST(root)\r\n",
    "        return root if b and l == m and r == n else None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def canMerge(self, trees: List[TreeNode]) -> Optional[TreeNode]:\n",
    "        n = len(trees)\n",
    "        if n == 1:\n",
    "            return trees[0]\n",
    "\n",
    "        l = [1] * n\n",
    "        vals = defaultdict(set)\n",
    "        for i,t in enumerate(trees):\n",
    "            for j,x in enumerate([t.left, t.right], start=1):\n",
    "                if x:\n",
    "                    l[i] += 1\n",
    "                    vals[x.val].add((i,j))\n",
    "                if l[i] > 1:\n",
    "                    vals[t.val].add((i,0))\n",
    "        # check single nodes\n",
    "        for i in range(n):\n",
    "            if l[i] == 1 and trees[i].val not in vals:\n",
    "                return\n",
    "        \n",
    "        # merge\n",
    "        isRoot = [v > 1 for v in l]\n",
    "        for v,z in vals.items():\n",
    "            if len(z) == 1:\n",
    "                continue\n",
    "            if len(z) >= 3:\n",
    "                return\n",
    "            z = sorted(z, key=lambda a: a[-1])\n",
    "            i, a = z[0]\n",
    "            j, b = z[1]\n",
    "            if not (0 == a < b):\n",
    "                return\n",
    "            if b == 1:\n",
    "                trees[j].left = trees[i]\n",
    "            else:\n",
    "                trees[j].right = trees[i]\n",
    "            isRoot[i] = False\n",
    "\n",
    "        if sum(isRoot) != 1:\n",
    "            return\n",
    "        root = trees[isRoot.index(True)]\n",
    "        \n",
    "        seen = set()\n",
    "        def isBST(x, l, r):\n",
    "            if not x:\n",
    "                return True\n",
    "            if not (l < x.val < r):\n",
    "                return False\n",
    "            if not isBST(x.left, l, x.val):\n",
    "                return False\n",
    "            if not isBST(x.right, x.val, r):\n",
    "                return False\n",
    "            seen.add(x.val)\n",
    "            return True\n",
    "        \n",
    "        if not isBST(root, -math.inf, math.inf):\n",
    "            return\n",
    "        if len(seen) != len(vals):\n",
    "            return\n",
    "        return root"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def canMerge(self, trees: List[TreeNode]) -> Optional[TreeNode]:\n",
    "        n = len(trees)\n",
    "        if n == 1:\n",
    "            return trees[0]\n",
    "\n",
    "        l = [1] * n\n",
    "        vals = defaultdict(set)\n",
    "        for i,t in enumerate(trees):\n",
    "            for j,x in enumerate([t.left, t.right], start=1):\n",
    "                if x:\n",
    "                    l[i] += 1\n",
    "                    vals[x.val].add((i,j))\n",
    "                if l[i] > 1:\n",
    "                    vals[t.val].add((i,0))\n",
    "        # check single nodes\n",
    "        for i in range(n):\n",
    "            if l[i] == 1 and trees[i].val not in vals:\n",
    "                return\n",
    "        \n",
    "        # merge\n",
    "        isRoot = [v > 1 for v in l]\n",
    "        for v,z in vals.items():\n",
    "            print(v, [x for x in z])\n",
    "            if len(z) == 1:\n",
    "                continue\n",
    "            if len(z) >= 3:\n",
    "                return\n",
    "            z = sorted(z, key=lambda a: a[-1])\n",
    "            i, a = z[0]\n",
    "            j, b = z[1]\n",
    "            if not (0 == a < b):\n",
    "                return\n",
    "            if b == 1:\n",
    "                trees[j].left = trees[i]\n",
    "            else:\n",
    "                trees[j].right = trees[i]\n",
    "            isRoot[i] = False\n",
    "\n",
    "        if sum(isRoot) != 1:\n",
    "            return\n",
    "        root = trees[isRoot.index(True)]\n",
    "        \n",
    "        seen = set()\n",
    "        def isBST(x, l, r):\n",
    "            if not x:\n",
    "                return True\n",
    "            if not (l < x.val < r):\n",
    "                return False\n",
    "            if not isBST(x.left, l, x.val):\n",
    "                return False\n",
    "            if not isBST(x.right, x.val, r):\n",
    "                return False\n",
    "            seen.add(x.val)\n",
    "            return True\n",
    "        # prev = -math.inf\n",
    "        # def isBST(x):\n",
    "        #     nonlocal prev\n",
    "        #     if x.left and isBST(x.left) == False:\n",
    "        #         return False\n",
    "        #     if prev >= x.val:\n",
    "        #         return False\n",
    "        #     prev = x.val\n",
    "        #     if x.right and isBST(x.right) == False:\n",
    "        #         return False\n",
    "        #     return True\n",
    "        \n",
    "        if not isBST(root, -math.inf, math.inf):\n",
    "            return\n",
    "        if len(seen) != len(vals):\n",
    "            return\n",
    "        return root"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        tmp = list2\n",
    "        b_end = tmp\n",
    "        while tmp!=None:\n",
    "            if tmp.next!=None:\n",
    "                b_end = tmp.next\n",
    "            tmp = tmp.next\n",
    "        index = 0\n",
    "        res = None\n",
    "        if a == 0:\n",
    "            res = list2\n",
    "        else:\n",
    "            res = list1\n",
    "        tmp = list1\n",
    "        while tmp!=None:\n",
    "            if index+1 == a:\n",
    "                k = tmp.next\n",
    "                tmp.next = list2\n",
    "                tmp = k\n",
    "                index += 1 \n",
    "                continue\n",
    "            if index == b:\n",
    "                b_end.next = tmp.next\n",
    "            tmp = tmp.next\n",
    "            index += 1\n",
    "        return res\n",
    "            \n",
    "            \n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        start = ListNode(0)\n",
    "        t0 = start\n",
    "        start.next = list1\n",
    "        #实例1： 先找到2（t0）\n",
    "        save_a = a\n",
    "        while(a):\n",
    "            t0 = t0.next\n",
    "            a -= 1\n",
    "        #print(t0.val)\n",
    "        t1 = t0\n",
    "        b = b - save_a + 2\n",
    "        #print(b)\n",
    "        while(b):\n",
    "            t1 = t1.next\n",
    "            b -= 1\n",
    "        #print(t1.val)\n",
    "        #插入\n",
    "        t0.next = list2\n",
    "        #list2的最后一个\n",
    "        while(list2.next):\n",
    "            list2 = list2.next\n",
    "        list2.next = t1 \n",
    "        return start.next\n",
    "\n",
    "        \n",
    "        \n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        fast, slow = list1, list1\n",
    "        k = b - a + 1\n",
    "        for _ in range(k):\n",
    "            fast = fast.next\n",
    "        for _ in range(a-1):\n",
    "            slow = slow.next\n",
    "            fast = fast.next\n",
    "        end = fast.next\n",
    "        pre, rear = list2, list2\n",
    "        while rear.next:\n",
    "            rear = rear.next\n",
    "        slow.next = pre\n",
    "        rear.next = end\n",
    "        return list1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        pre = dummy = ListNode(-1)\n",
    "        pre.next = list1\n",
    "        prea  = pre\n",
    "        for i in range(a):\n",
    "            prea = prea.next\n",
    "        nodeb = list1    \n",
    "        for i in range(b):\n",
    "            nodeb = nodeb.next\n",
    "        prea.next = list2    \n",
    "        cur = list2\n",
    "        while cur.next:\n",
    "            cur = cur.next\n",
    "        cur.next = nodeb.next    \n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        l = list1\n",
    "        for _ in range(a - 1):\n",
    "            l = l.next\n",
    "        r = l.next\n",
    "        for _ in range(b - a + 1):\n",
    "            r = r.next\n",
    "        l.next = list2\n",
    "        tail = list2\n",
    "        while tail.next: tail = tail.next\n",
    "        tail.next = r\n",
    "        \n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        prea = dummy = ListNode(0)\n",
    "        dummy.next = list1\n",
    "        nxb = None\n",
    "        b -= a\n",
    "        while a:\n",
    "            prea = prea.next\n",
    "            a -= 1\n",
    "        nxb = prea.next\n",
    "        while b:\n",
    "            nxb = nxb.next\n",
    "            b -= 1\n",
    "        nxb = nxb.next\n",
    "\n",
    "        head = list2\n",
    "        while head and head.next:\n",
    "            head = head.next\n",
    "\n",
    "        prea.next = list2\n",
    "        head.next = nxb\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        head = ListNode(0)\n",
    "        curr = head\n",
    "        i = 0\n",
    "        while i < a:\n",
    "            i += 1\n",
    "            curr.next = list1\n",
    "            list1 = list1.next\n",
    "            curr = curr.next\n",
    "        while i < b:\n",
    "            i += 1\n",
    "            list1 = list1.next\n",
    "        curr.next = list2\n",
    "        while curr.next:\n",
    "            curr = curr.next\n",
    "        curr.next = list1.next\n",
    "        return head.next\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        hashmap1 = dict()\n",
    "        i = 0\n",
    "        node1 = list1\n",
    "        while node1:\n",
    "            hashmap1[i] = node1\n",
    "            i += 1\n",
    "            node1 = node1.next\n",
    "        hashmap1[a-1].next = list2\n",
    "        node2 = list2\n",
    "        while node2.next:\n",
    "            node2 = node2.next\n",
    "        node2.next = hashmap1.get(b+1, None)\n",
    "        hashmap1[b].next = None\n",
    "        return hashmap1[0]\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        endnote = list1\n",
    "        count = -1\n",
    "        while endnote:\n",
    "            count += 1\n",
    "            if count == b:\n",
    "                endnote = endnote.next\n",
    "                break\n",
    "            endnote = endnote.next\n",
    "\n",
    "        cur2 = list2\n",
    "        while cur2:\n",
    "            if cur2.next == None:\n",
    "                cur2.next = endnote\n",
    "                break\n",
    "            cur2 = cur2.next\n",
    "\n",
    "        cur = list1\n",
    "        count = 0\n",
    "        while cur:\n",
    "            count += 1\n",
    "            if count == a:\n",
    "                cur.next = list2\n",
    "                break\n",
    "            cur = cur.next\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        \n",
    "        \n",
    "        \n",
    "        # my solution ... 432 ms ... 19.6 MB ... \n",
    "        #  time: O(n+m)\n",
    "        # space: O(n)\n",
    "        \n",
    "        idx2nod = {}\n",
    "        node = list1\n",
    "        index = 0\n",
    "        while node:\n",
    "            idx2nod[index] = node\n",
    "            index += 1\n",
    "            node = node.next\n",
    "        node = list2\n",
    "        while node.next:\n",
    "            node = node.next\n",
    "        idx2nod[a-1].next = list2\n",
    "        node.next = idx2nod[b+1]\n",
    "        return list1\n",
    "        \n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        aa = []\n",
    "        tmp = list1\n",
    "        while tmp is not None:\n",
    "            aa.append(tmp.val)\n",
    "            tmp = tmp.next\n",
    "        def make(a):\n",
    "            ret = ListNode()\n",
    "            now = ret\n",
    "            for x in a:\n",
    "                tmp = ListNode(x)\n",
    "                now.next = tmp\n",
    "                now = tmp\n",
    "            return ret.next, now\n",
    "        a1,t1 = make(aa[:a])\n",
    "        a2,_ = make(aa[b+1:])\n",
    "        t1.next = list2\n",
    "        head = list2\n",
    "        while head.next is not None:\n",
    "            head = head.next\n",
    "        head.next=a2\n",
    "        return a1\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        ans = ListNode(0)\n",
    "        ans.next = list1\n",
    "        q = list2\n",
    "        while list2 and list2.next:\n",
    "            list2 = list2.next\n",
    "        count = 0\n",
    "        p = list1\n",
    "        while p:\n",
    "            count += 1\n",
    "            if count == a:\n",
    "                pre = p\n",
    "            p = p.next\n",
    "            if count == b+1:\n",
    "                break\n",
    "        pre.next = q\n",
    "        list2.next = p\n",
    "        return ans.next\n",
    "\n",
    "        \n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        # dummy = ListNode(0)\n",
    "        # dummy.next = list1\n",
    "        # temp = dummy\n",
    "        temp = list1\n",
    "        for i in range(a-1):\n",
    "            temp = temp.next\n",
    "        prev = temp\n",
    "               \n",
    "        for j in range(b-a+2):\n",
    "            temp = temp.next\n",
    "        last = temp\n",
    "\n",
    "        cur = list2\n",
    "        while cur.next:\n",
    "            cur = cur.next\n",
    "        prev.next = list2\n",
    "        cur.next = last\n",
    "\n",
    "        return list1\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        node = list1\n",
    "        length = 0\n",
    "        while list1:\n",
    "            if length == a - 1:\n",
    "                pre = list1\n",
    "            if length == b + 1:\n",
    "                nex = list1\n",
    "            length += 1\n",
    "            list1 = list1.next\n",
    "        pre.next = list2\n",
    "        while list2.next:\n",
    "            list2 = list2.next\n",
    "        list2.next = nex\n",
    "        return node"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        dummy = ListNode(-1)\n",
    "        dummy.next = list1\n",
    "        slow = fast = dummy\n",
    "        for _ in range(b-a+1):\n",
    "            fast = fast.next\n",
    "        for _ in range(a):\n",
    "            slow = slow.next\n",
    "            fast = fast.next\n",
    "        \n",
    "        tail_list2 = list2\n",
    "        while tail_list2.next:\n",
    "            tail_list2 = tail_list2.next\n",
    "\n",
    "        slow.next = list2\n",
    "        tail_list2.next = fast.next\n",
    "        fast.next = None\n",
    "\n",
    "        return dummy.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        cur1 = list1\n",
    "        cur2 = list2\n",
    "        prev = prev1 = ListNode()\n",
    "        \n",
    "        n = 0\n",
    "        while cur1:\n",
    "            if n < a:\n",
    "                prev1.next = cur1\n",
    "                prev1 = prev1.next\n",
    "                cur1 = cur1.next\n",
    "           \n",
    "            elif a <= n < b:\n",
    "                cur1 = cur1.next\n",
    "            elif n == b:\n",
    "                cur1 = cur1.next\n",
    "                while cur2:\n",
    "                   prev1.next = cur2\n",
    "                   prev1 = prev1.next\n",
    "                   cur2 = cur2.next\n",
    "      \n",
    "            elif n > a:\n",
    "\n",
    "                prev1.next = cur1\n",
    "                prev1 = prev1.next\n",
    "                cur1 = cur1.next\n",
    "            n = n + 1\n",
    "        return prev.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        # 连接list2尾部和b+1个节点\n",
    "        L1 = list1\n",
    "        L2 = list2\n",
    "        while L2.next:\n",
    "            L2 = L2.next\n",
    "        while b >= 0:\n",
    "            L1 = L1.next\n",
    "            b -= 1\n",
    "        L2.next = L1\n",
    "\n",
    "        # 连接list2头部\n",
    "        # 这里用哑结点更方便一点\n",
    "        L1 = ListNode(-1, list1)\n",
    "        while a > 0:\n",
    "            L1 = L1.next\n",
    "            a -= 1\n",
    "        L1.next = list2\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        if not list1:\n",
    "            return list1\n",
    "        dummy = ListNode(0)\n",
    "        dummy.next = list1\n",
    "        # 找到a-1节点\n",
    "        nodeA = list1\n",
    "        for i in range(a-1):\n",
    "            nodeA = nodeA.next\n",
    "        # 找到b+1节点\n",
    "        nodeB = nodeA\n",
    "        for i in range(a-1, b+1):\n",
    "            nodeB = nodeB.next\n",
    "\n",
    "        # 找到list2的尾节点\n",
    "        tail = list2\n",
    "        while tail.next:\n",
    "            tail = tail.next\n",
    "        # 把list2接入到list1的a，b位置\n",
    "        tail.next = nodeB\n",
    "        nodeA.next = list2\n",
    "\n",
    "        return dummy.next\n",
    "            \n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        point = res = ListNode(0)\n",
    "        res.next = list1\n",
    "        res = res.next\n",
    "        for i in range(a-1):\n",
    "            list1 = list1.next\n",
    "        tmp = list1.next\n",
    "        for i in range(b-a):\n",
    "            tmp = tmp.next\n",
    "        list1.next = list2\n",
    "        while list1.next:\n",
    "            list1 = list1.next\n",
    "        list1.next = tmp.next\n",
    "        return point.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        pA = list1\n",
    "        for i in range(a-1):\n",
    "            pA = pA.next\n",
    "        pB = pA\n",
    "        for i in range(b-a+1):\n",
    "            pB = pB.next\n",
    "        pA.next = list2\n",
    "        p = list2\n",
    "        while p.next:\n",
    "            p = p.next\n",
    "        p.next = pB.next\n",
    "        return list1\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        dummy = ListNode(-1, list1)\n",
    "        curA = dummy\n",
    "        tmp = list1\n",
    "        # 找到b, 标记b+1\n",
    "        for _ in range(b):\n",
    "            tmp = tmp.next\n",
    "        curB = tmp.next\n",
    "        tmp.next = None\n",
    "\n",
    "        # 找到a, 标记a-1\n",
    "        for _ in range(a):\n",
    "            curA = curA.next\n",
    "        curA.next = None\n",
    "\n",
    "        # 遍历list2, 标记尾节点tail\n",
    "        cur = list2\n",
    "        while cur.next:\n",
    "            cur = cur.next\n",
    "        \n",
    "        # 整合链表\n",
    "        curA.next = list2\n",
    "        cur.next = curB\n",
    "        return dummy.next\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        p1, p2 = list1, list1\n",
    "        while a > 1:\n",
    "            p1 = p1.next\n",
    "            a -= 1\n",
    "        while b > -1:\n",
    "            p2 = p2.next\n",
    "            b -= 1\n",
    "        \n",
    "        tail = list2\n",
    "        while tail.next:\n",
    "            tail = tail.next\n",
    "\n",
    "        p1.next = list2\n",
    "        tail.next = p2\n",
    "\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        \"\"\"\n",
    "          因为a>=1,所以不会删除第一个节点\n",
    "        \"\"\"\n",
    "        node_num = 0\n",
    "        cur = list1\n",
    "        while cur and node_num<a-1:\n",
    "            cur = cur.next\n",
    "            node_num += 1\n",
    "        cur1 = cur\n",
    "        while cur1 and node_num<=b:\n",
    "            cur1 = cur1.next\n",
    "            node_num += 1\n",
    "        cur.next = list2\n",
    "        while cur.next:\n",
    "            cur = cur.next\n",
    "        cur.next = cur1\n",
    "        return list1\n",
    "        \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        ind = 0\n",
    "        p = list1\n",
    "        while p:\n",
    "            if ind == a-1:start = p\n",
    "            if ind == b+1:end = p\n",
    "            p = p.next\n",
    "            ind = ind+1\n",
    "        start.next = list2\n",
    "        while list2.next:\n",
    "            list2 = list2.next\n",
    "        list2.next = end\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        offseta = a\n",
    "        offsetb = b\n",
    "        offset = max(a, b)\n",
    "        a = b = None\n",
    "\n",
    "        a_pre = None\n",
    "        cur = list1\n",
    "        offseti = 0\n",
    "        while cur and offseti <= offset:\n",
    "            if offseti == offseta-1:\n",
    "                a_pre = cur\n",
    "            if offseti == offsetb:\n",
    "                b = cur\n",
    "\n",
    "            offseti += 1\n",
    "            cur = cur.next\n",
    "\n",
    "        tail2 = list2\n",
    "        while tail2 and tail2.next:\n",
    "            tail2 = tail2.next\n",
    "\n",
    "        if not a_pre and not b:\n",
    "            return list2\n",
    "\n",
    "        if not a_pre and b:\n",
    "            if tail2:\n",
    "                tail2.next = b.next\n",
    "            if not list2:\n",
    "                return b.next\n",
    "            return list2\n",
    "\n",
    "        if a_pre and not b:\n",
    "            a_pre.next = None\n",
    "            a_pre.next = list2\n",
    "            return list1\n",
    "\n",
    "        if a_pre and b:\n",
    "            if not list2:\n",
    "                a_pre.next = b.next\n",
    "            else:\n",
    "                a_pre.next = list2\n",
    "                tail2.next = b.next\n",
    "            return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        node = list1\n",
    "        for _ in range(a-1):\n",
    "            node = node.next\n",
    "        part3_node = node\n",
    "        for _ in range(b-a+2):\n",
    "            part3_node = part3_node.next\n",
    "        node2 = list2\n",
    "        while node2.next:\n",
    "            node2 = node2.next\n",
    "        node.next = list2\n",
    "        node2.next = part3_node\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        dummy = ListNode(-1, list1)\n",
    "        curr = dummy\n",
    "        start = 0\n",
    "        while list1:\n",
    "            if start == a:\n",
    "                while list2:\n",
    "                    curr.next = list2\n",
    "                    list2 = list2.next\n",
    "                    curr = curr.next\n",
    "            while start >= a and start <= b:\n",
    "                list1 = list1.next\n",
    "                start += 1\n",
    "            start += 1\n",
    "            curr.next = list1\n",
    "            curr = curr.next\n",
    "            list1 = list1.next\n",
    "        return dummy.next\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        p=q=list1\n",
    "        for _ in range(a-1):\n",
    "            p=p.next\n",
    "        for _ in range(b):\n",
    "            q=q.next\n",
    "        p.next=list2\n",
    "        while p.next:\n",
    "            p=p.next\n",
    "        p.next=q.next\n",
    "        q.next=None\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        cur_node = list1\n",
    "        c = 0\n",
    "        while cur_node:\n",
    "            if c == a - 1:\n",
    "                st_node = cur_node\n",
    "            if c == b + 1:\n",
    "                ed_node = cur_node\n",
    "            cur_node = cur_node.next\n",
    "            c += 1\n",
    "        \n",
    "        cur_node = list1\n",
    "        while cur_node:\n",
    "            if cur_node == st_node:\n",
    "                cur_node.next = list2\n",
    "                while list2.next:\n",
    "                    list2 = list2.next\n",
    "                list2.next = ed_node\n",
    "                cur_node = ed_node\n",
    "            cur_node = cur_node.next\n",
    "        \n",
    "        return list1\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "        # dummy_node = ListNode()\n",
    "        # dummy_node.next = list1\n",
    "        # while \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        p=q=list1\n",
    "        for _ in range(a-1):p=p.next#遍历到a\n",
    "        for _ in range(b):q=q.next#找到b+1\n",
    "        p.next=list2\n",
    "        while p.next:\n",
    "            p=p.next\n",
    "        p.next=q.next\n",
    "        q.next=None\n",
    "        return list1\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        p=q=list1\n",
    "        for _ in range(a-1):p=p.next#遍历到a-1节点\n",
    "        for _ in range(b):q=q.next#找到b\n",
    "        p.next=list2 #a-1指向Liste2\n",
    "        while p.next:\n",
    "            p=p.next #遍历到末尾\n",
    "        p.next=q.next\n",
    "        q.next=None\n",
    "        return list1\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        p,q = list1,list1\n",
    "        for i in range(a-1):\n",
    "            p = p.next\n",
    "        for i in range(b):\n",
    "            q = q.next\n",
    "        p.next = list2\n",
    "        while p.next:\n",
    "            p = p.next\n",
    "        p.next = q.next\n",
    "        q.next = None\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        # 需要寻找a的前缀和b的next\n",
    "        protect = list1\n",
    "        list1_index = 1\n",
    "        while list1.next:\n",
    "            if list1_index == a:\n",
    "                # 记录下来a节点的前缀位置\n",
    "                flag_a_prior = list1\n",
    "            if list1_index == b:\n",
    "                # 记录下来b节点的next位置\n",
    "                flag_b_next = list1.next.next\n",
    "            list1 = list1.next\n",
    "            list1_index += 1\n",
    "        # 把list2拼接在a的前缀的next\n",
    "        flag_a_prior.next = list2\n",
    "        # 找到list2的尾指针\n",
    "        while list2.next:\n",
    "            list2 = list2.next\n",
    "        # 把b的next拼接在list2尾指针的位置\n",
    "        list2.next = flag_b_next\n",
    "        return protect\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        cur=list1\n",
    "        for i in range(a-1):\n",
    "            cur=cur.next\n",
    "        aft=list1\n",
    "        for i in range(b):\n",
    "            aft=aft.next\n",
    "        cur.next=list2\n",
    "        while cur.next:\n",
    "            cur=cur.next\n",
    "        cur.next=aft.next\n",
    "        aft.next=None\n",
    "        return list1\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        preA = list1\n",
    "        for _ in range(a - 1):\n",
    "            preA = preA.next\n",
    "        preB = preA\n",
    "        for _ in range(b - a + 2):\n",
    "            preB = preB.next\n",
    "        preA.next = list2\n",
    "        while list2.next:\n",
    "            list2 = list2.next\n",
    "        list2.next = preB\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        p,q = list1,list1\n",
    "        for i in range(a-1):\n",
    "            p = p.next\n",
    "        for i in range(b):\n",
    "            q = q.next\n",
    "        p.next = list2\n",
    "        while p.next:\n",
    "            p = p.next\n",
    "        p.next = q.next\n",
    "        q.next = None\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        site=0\n",
    "        site2=0\n",
    "        len2=0\n",
    "        cur1=list1\n",
    "        cur2=list2\n",
    "        while cur2:\n",
    "            len2+=1\n",
    "            cur2=cur2.next\n",
    "        while cur1:\n",
    "            site2+=1\n",
    "            cur1=cur1.next\n",
    "            if site2==b:\n",
    "                end=cur1.next\n",
    "                break\n",
    "        cur1=list1\n",
    "        while cur1:\n",
    "            site+=1\n",
    "            if site==a:\n",
    "                cur1.next=list2\n",
    "                while cur1.next:\n",
    "                    cur1=cur1.next\n",
    "                    site+=1\n",
    "                cur1.next=end\n",
    "                break\n",
    "            cur1=cur1.next\n",
    "        return list1\n",
    "\n",
    "    \n",
    "\n",
    "                    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        def find(h, pos):\n",
    "            now = h\n",
    "            if pos == -1:\n",
    "                while now.next:\n",
    "                    now = now.next\n",
    "            else:\n",
    "                for i in range(pos):\n",
    "                    now = now.next\n",
    "            return now\n",
    "\n",
    "        pre = find(list1, a - 1)\n",
    "        tail = find(list1, b + 1)\n",
    "        pre.next =  list2\n",
    "        find(list2, -1).next = tail\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "\n",
    "        # 获取索引为a-1的节点\n",
    "        aprev = list1\n",
    "        for _ in range(a-1):\n",
    "            aprev = aprev.next\n",
    "        \n",
    "        # 获取索引为b+1的节点\n",
    "        bnext = aprev\n",
    "        for _ in range(b-a+2):\n",
    "            bnext = bnext.next\n",
    "\n",
    "        # 合并\n",
    "        aprev.next = list2\n",
    "        while aprev.next:\n",
    "            aprev = aprev.next\n",
    "        aprev.next = bnext\n",
    "\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        cur=list1\n",
    "        i=0\n",
    "        while cur:\n",
    "            if i==a-1:\n",
    "                node1=cur\n",
    "            elif i==b:\n",
    "                node2=cur\n",
    "                break\n",
    "            i+=1\n",
    "            cur=cur.next\n",
    "        node1.next=list2\n",
    "        while list2.next:\n",
    "            list2=list2.next\n",
    "        list2.next=node2.next\n",
    "        node2.next=None\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        cur = 0\n",
    "        left = list1\n",
    "        pre = None\n",
    "        while cur!=a:\n",
    "            pre = left\n",
    "            left = left.next\n",
    "            cur+=1\n",
    "        right = left\n",
    "        while cur!=b:\n",
    "            right = right.next\n",
    "            cur+=1\n",
    "        ans = None\n",
    "        cur = list2\n",
    "        while cur.next is not None:\n",
    "            cur = cur.next\n",
    "        cur.next = right.next\n",
    "        if pre is None:\n",
    "            ans = list2\n",
    "        else:\n",
    "            ans = list1\n",
    "            pre.next = list2\n",
    "            cur = list2\n",
    "        return ans\n",
    "\n",
    "        \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        p = q = list1\n",
    "        for _ in range(a-1):\n",
    "            p = p.next\n",
    "        for _ in range(b):\n",
    "            q = q.next\n",
    "        p.next = list2\n",
    "        while p.next:\n",
    "            p = p.next\n",
    "        p.next = q.next\n",
    "        q.next = None\n",
    "        return list1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        index = 0\n",
    "        pivot = list1\n",
    "        while index < a-1:\n",
    "            pivot = pivot.next\n",
    "            index += 1\n",
    "        left = pivot\n",
    "        while index <= b:\n",
    "            pivot = pivot.next\n",
    "            index +=1\n",
    "        right = pivot\n",
    "        left.next = list2\n",
    "        pivot = list2\n",
    "        while pivot.next!=None:\n",
    "            pivot = pivot.next\n",
    "        pivot.next = right\n",
    "        return list1\n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        lenth = 0\n",
    "        cur = list1\n",
    "        before_a = after_b = list1\n",
    "        for _ in range(a-1):\n",
    "            before_a = before_a.next\n",
    "        \n",
    "        for _ in range(b+1):\n",
    "            after_b = after_b.next\n",
    "        \n",
    "        before_a.next = list2\n",
    "        while before_a.next:\n",
    "            before_a = before_a.next\n",
    "        before_a.next = after_b\n",
    "\n",
    "        return list1\n",
    "        \n",
    "\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        p = q = list1\n",
    "        for _ in range(a - 1):\n",
    "            p = p.next\n",
    "        for _ in range(b):\n",
    "            q = q.next\n",
    "        # print(p.val,q.val)\n",
    "        p.next = list2\n",
    "        while p.next:\n",
    "            p = p.next\n",
    "        p.next = q.next\n",
    "        # print(list1)\n",
    "        # q.next = None\n",
    "        return list1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        lenth = 0\n",
    "        cur = cur_a = cur_b = list1\n",
    "        before_a = after_b = list1\n",
    "        while cur:\n",
    "            lenth += 1\n",
    "            if lenth == a:\n",
    "                before_a = cur\n",
    "            if lenth == b+1:\n",
    "                after_b = cur.next\n",
    "                cur.next = None\n",
    "                before_a.next = None\n",
    "                break\n",
    "            cur = cur.next\n",
    "\n",
    "        # list2的结尾\n",
    "        cur = list2\n",
    "        while cur.next:\n",
    "            cur = cur.next\n",
    "        before_a.next, cur.next = list2, after_b\n",
    "\n",
    "        return list1\n",
    "        \n",
    "\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        cache1 = []\n",
    "        cache2 = []\n",
    "        while list1:\n",
    "            cache1.append(list1)\n",
    "            list1 = list1.next\n",
    "        while list2:\n",
    "            cache2.append(list2)\n",
    "            list2 = list2.next\n",
    "        cache2[-1].next = cache1[b+1] if b+1<len(cache1) else None\n",
    "        if a-1>=0:\n",
    "            cache1[a-1].next = cache2[0]\n",
    "            return cache1[0]\n",
    "        else:\n",
    "            return cache2[0]\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        ans = ListNode(0, list1)\n",
    "        temp = ans\n",
    "        flag = 0\n",
    "        while flag < a:\n",
    "            flag += 1\n",
    "            temp = temp.next\n",
    "        temp2 = temp\n",
    "        while flag <= b:\n",
    "            temp2 = temp2.next\n",
    "            flag += 1\n",
    "        temp.next = list2\n",
    "        while temp.next:\n",
    "            temp = temp.next\n",
    "        temp.next = temp2.next\n",
    "        return ans.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        head = list1 \n",
    "        for _ in range(1, a):\n",
    "            list1 = list1.next \n",
    "        start = list1 \n",
    "        for _ in range(a, b+2):\n",
    "            list1 = list1.next\n",
    "        end = list1 \n",
    "        start.next = list2\n",
    "        while list2.next:\n",
    "            list2 = list2.next \n",
    "        list2.next = end\n",
    "        return head\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        node = list1\n",
    "        for _ in range(a - 1):\n",
    "            node = node.next\n",
    "        middle = node.next.next\n",
    "        node.next = list2\n",
    "\n",
    "        # 找到切断后右边最左的节点\n",
    "        for _ in range(b - a):\n",
    "            middle = middle.next\n",
    "        \n",
    "\n",
    "        # 找到list2的尾部\n",
    "        list2 = list2\n",
    "        while list2.next:\n",
    "            list2 = list2.next\n",
    "        \n",
    "        list2.next = middle\n",
    "        return list1\n",
    "        \n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\r\n",
    "# class ListNode:\r\n",
    "#     def __init__(self, val=0, next=None):\r\n",
    "#         self.val = val\r\n",
    "#         self.next = next\r\n",
    "class Solution:\r\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\r\n",
    "            \r\n",
    "            dummy = ListNode(0)\r\n",
    "            dummy.next = list1\r\n",
    "            pre = dummy\r\n",
    "            cur = list1\r\n",
    "            for _ in range(a):\r\n",
    "                pre = cur\r\n",
    "                cur = cur.next\r\n",
    "            pre.next = list2\r\n",
    "            while list2.next:\r\n",
    "                list2 = list2.next\r\n",
    "            for _ in range(b-a+1):\r\n",
    "                cur = cur.next\r\n",
    "            list2.next = cur\r\n",
    "            return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        cur1=list1\n",
    "        i=0\n",
    "        while i<a-1:\n",
    "            cur1=cur1.next\n",
    "            i+=1\n",
    "        cur2=cur1.next\n",
    "        cur1.next=list2\n",
    "        while cur1.next!=None:\n",
    "            cur1=cur1.next\n",
    "\n",
    "        while i<b:\n",
    "            cur2=cur2.next\n",
    "            i+=1\n",
    "        cur1.next=cur2\n",
    "        return list1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n",
    "        dummy = p = q = ListNode(0, list1)\n",
    "        for i in range(a):\n",
    "            p = p.next\n",
    "        for i in range(b + 2):\n",
    "            q = q.next\n",
    "        p.next = list2\n",
    "        p = list2\n",
    "        while p.next != None:\n",
    "            p = p.next\n",
    "        p.next = q\n",
    "        return dummy.next\n",
    "\n",
    "        \n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort()  # remember to sort!!!\n",
    "        res = []\n",
    "        for i in intervals:\n",
    "            if not res or res[-1][1] < i[0]:\n",
    "                res.append(i)\n",
    "            else:\n",
    "                res[-1][1] = max(res[-1][1], i[1])\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for an interval.\n",
    "# class Interval:\n",
    "#     def __init__(self, s=0, e=0):\n",
    "#         self.start = s\n",
    "#         self.end = e\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals):\n",
    "        out = []\n",
    "        for i in sorted(intervals, key=lambda x:x.start):\n",
    "            if out and out[-1].end >= i.start:\n",
    "                out[-1].end = max(out[-1].end, i.end)\n",
    "            else:\n",
    "                out.append(i)\n",
    "        \n",
    "        return out\n",
    "        \"\"\"\n",
    "        :type intervals: List[Interval]\n",
    "        :rtype: List[Interval]\n",
    "        \"\"\"\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for an interval.\n",
    "# class Interval:\n",
    "#     def __init__(self, s=0, e=0):\n",
    "#         self.start = s\n",
    "#         self.end = e\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals):\n",
    "        \"\"\"\n",
    "        :type intervals: List[Interval]\n",
    "        :rtype: List[Interval]\n",
    "        \"\"\"\n",
    "        if len(intervals) == 0:\n",
    "            return []\n",
    "        intervals = sorted(intervals, key = lambda x:x.start)\n",
    "        res = [intervals[0]]\n",
    "        for node in intervals[1:]:\n",
    "            if node.start<=res[-1].end:\n",
    "                res[-1].end = max(node.end,res[-1].end)\n",
    "            else:\n",
    "                res.append(node)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for an interval.\n",
    "# class Interval:\n",
    "#     def __init__(self, s=0, e=0):\n",
    "#         self.start = s\n",
    "#         self.end = e\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals):\n",
    "        \"\"\"\n",
    "        :type intervals: List[Interval]\n",
    "        :rtype: List[Interval]\n",
    "        \"\"\"\n",
    "        if len(intervals) <= 1:\n",
    "            return intervals\n",
    "        intervals.sort(key=lambda x: x.start)\n",
    "        cur = intervals[0]\n",
    "        ans = []\n",
    "        for i in range(1, len(intervals)):\n",
    "            if cur.end < intervals[i].start:\n",
    "                # non-overlap\n",
    "                ans.append(cur)\n",
    "                cur = intervals[i]\n",
    "            else:\n",
    "                # overlap\n",
    "                cur.end = max(cur.end, intervals[i].end)\n",
    "        if not ans or ans[-1].end < cur.start:\n",
    "            ans.append(cur)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals):\n",
    "        \"\"\"\n",
    "        :type intervals: List[Interval]\n",
    "        :rtype: List[Interval]\n",
    "        \"\"\"\n",
    "        ans = []\n",
    "        # self.quicksort(intervals, 0, len(intervals)-1)\n",
    "        intervals = sorted(intervals, key=lambda x: x.start)\n",
    "        for item in intervals:\n",
    "            if not ans or item.start > ans[-1].end:\n",
    "                ans.append(item)\n",
    "            elif item.end > ans[-1].end:\n",
    "                ans[-1].end = item.end\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for an interval.\n",
    "# class Interval:\n",
    "#     def __init__(self, s=0, e=0):\n",
    "#         self.start = s\n",
    "#         self.end = e\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals):\n",
    "        \"\"\"\n",
    "        :type intervals: List[Interval]\n",
    "        :rtype: List[Interval]\n",
    "        \"\"\"\n",
    "        res = []\n",
    "        if intervals:\n",
    "            i = 0\n",
    "            while intervals:\n",
    "                flag = False\n",
    "                start, end = intervals[0].start, intervals[0].end\n",
    "                j = 1\n",
    "                \n",
    "                while j < len(intervals):\n",
    "                    if (intervals[j].start >= start and intervals[j].start <= end) or (intervals[j].end >= start and intervals[j].end <= end) or (intervals[j].start <= start and intervals[j].end >= end):\n",
    "                        start = min(intervals[j].start, start)\n",
    "                        end = max(intervals[j].end, end)\n",
    "                        del intervals[j]\n",
    "                        intervals[0] = Interval(start, end)\n",
    "                        flag = True\n",
    "                        \n",
    "                    j += 1\n",
    "                    print(j)\n",
    "                if flag == False:\n",
    "                    del intervals[0]\n",
    "                    res.append([start, end])\n",
    "                print(start, end)\n",
    "                \n",
    "                #print(i, intervals)\n",
    "        return res\n",
    "                        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for an interval.\n",
    "# class Interval:\n",
    "#     def __init__(self, s=0, e=0):\n",
    "#         self.start = s\n",
    "#         self.end = e\n",
    "from itertools import chain\n",
    "class Solution:\n",
    "    def merge(self, intervals):\n",
    "        \"\"\"\n",
    "        :type intervals: List[Interval]\n",
    "        :rtype: List[Interval]\n",
    "        \"\"\"\n",
    "        ends = list(chain.from_iterable(((i.start, -1), (i.end, 1)) for i in intervals))\n",
    "        ends.sort();\n",
    "        dep = 0\n",
    "        result = []\n",
    "        for i, e in ends:\n",
    "            if dep == 0:\n",
    "                start = i\n",
    "            dep += e\n",
    "            if dep == 0:\n",
    "                result.append([start, i])\n",
    "        return result\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for an interval.\n",
    "# class Interval:\n",
    "#     def __init__(self, s=0, e=0):\n",
    "#         self.start = s\n",
    "#         self.end = e\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: 'List[Interval]') -> 'List[Interval]':\n",
    "        _intervals = [[x.start, x.end] for x in intervals]\n",
    "        _intervals.sort(key=lambda x: (x[0], x[1]))\n",
    "\n",
    "        i = 1\n",
    "        while i < len(_intervals):\n",
    "            if _intervals[i][0] <= _intervals[i-1][1]:\n",
    "                _intervals[i-1][0] = min(_intervals[i][0], _intervals[i-1][0])\n",
    "                _intervals[i-1][1] = max(_intervals[i][1], _intervals[i-1][1])\n",
    "                del _intervals[i]\n",
    "            else:\n",
    "                i += 1\n",
    "\n",
    "        return _intervals\n",
    "            \n",
    "            \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for an interval.\n",
    "# class Interval:\n",
    "#     def __init__(self, s=0, e=0):\n",
    "#         self.start = s\n",
    "#         self.end = e\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals):\n",
    "        \"\"\"\n",
    "        :type intervals: List[Interval]\n",
    "        :rtype: List[Interval]\n",
    "        \"\"\"\n",
    "        intervals = sorted(intervals, key = lambda x: x.start)\n",
    "        res = []\n",
    "        for ele in intervals:\n",
    "            if not res:\n",
    "                res.append(ele)\n",
    "            elif ele.start <= res[-1].end:\n",
    "                res[-1].end = max(ele.end, res[-1].end)\n",
    "            else:\n",
    "                res.append(ele)\n",
    "            print(\"ele: {}, {}\".format(ele.start, ele.end))\n",
    "            self.printEle(res)\n",
    "        return res\n",
    "    def printEle(self, intervals):\n",
    "        for i in intervals:\n",
    "            print(i.start, i.end, end = ',')\n",
    "        print('\\n')\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for an interval.\n",
    "# class Interval:\n",
    "#     def __init__(self, s=0, e=0):\n",
    "#         self.start = s\n",
    "#         self.end = e\n",
    "from operator import itemgetter\n",
    "class Solution:\n",
    "    def merge(self, _intervals):\n",
    "        \"\"\"\n",
    "        :type intervals: List[Interval]\n",
    "        :rtype: List[Interval]\n",
    "        \"\"\"\n",
    "        intervals = [[x.start,x.end] for x in _intervals]\n",
    "        if intervals == []:\n",
    "            return []\n",
    "        while True:\n",
    "            intervals.sort(key=itemgetter(0,1))\n",
    "            count = 0\n",
    "            for i in range(len(intervals)-1):\n",
    "                if intervals[i+1][0] <= intervals[i][1] <=intervals[i+1][1] or intervals[i][0] <=intervals[i+1][1] <= intervals[i][1]:\n",
    "                    intervals[i][0] = min(intervals[i][0],intervals[i+1][0])\n",
    "                    intervals[i][1] = max(intervals[i][1],intervals[i+1][1])\n",
    "                    intervals[i+1][0] = min(intervals[i][0], intervals[i + 1][0])\n",
    "                    intervals[i+1][1] = max(intervals[i][1], intervals[i + 1][1])\n",
    "                else:\n",
    "                    count+=1\n",
    "                    continue\n",
    "            if count == len(intervals)-1:\n",
    "                break\n",
    "            temp_l = list(set([str(i) for i in intervals]))\n",
    "            intervals = [eval((i)) for i in temp_l]\n",
    "        return intervals\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals):\n",
    "        if not intervals:\n",
    "            return []\n",
    "        intervals.sort()\n",
    "        res = []\n",
    "        cur = intervals[0]\n",
    "        for i in range(1, len(intervals)):\n",
    "            if intervals[i][0] <= cur[1]:\n",
    "                cur[1] = max(cur[1], intervals[i][1])\n",
    "            else:\n",
    "                res.append(cur)\n",
    "                cur = intervals[i]\n",
    "        res.append(cur)\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        # sorted 区间list，便于后续遍历\n",
    "        intervals = sorted(intervals)\n",
    "        res = []\n",
    "        i = 0\n",
    "        # 对于每一个区间，我们首先判断它自己的最大值和后面一个区间的最小值哪个大\n",
    "        # 如果可以merge，那么还要判断两者的最大值哪个大，以确定merge后的区间上限\n",
    "        # 首先使用left和right来代表intervals的上下限\n",
    "        # 同时有一个指针指向自己，merge前的比较要保证指针合法\n",
    "        # merge后指针加一，同时由于指针指向的是自己，在无法merge后，还要再加以才能找到下一个起始区间\n",
    "        while i < len(intervals):\n",
    "            left = intervals[i][0]\n",
    "            right = intervals[i][1]\n",
    "            while i+1 < len(intervals) and right >= intervals[i+1][0]:\n",
    "                right = max(right,intervals[i+1][1])\n",
    "                i += 1\n",
    "            res.append([left,right])\n",
    "            i += 1\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        res = []\n",
    "        intervals.sort(key=lambda x: x[0])\n",
    "        for i in intervals:\n",
    "            if res and i[0] <= res[-1][1]:\n",
    "                res[-1][1] = max(res[-1][1], i[1])\n",
    "            else:\n",
    "                #res.append(i)\n",
    "                res += i,\n",
    "        return res\n",
    "            \n",
    "        \n",
    "                \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort()\n",
    "        ans=[intervals[0]]\n",
    "        intervals=intervals[1:]\n",
    "        while len(intervals)>0:\n",
    "            if ans[-1][1]>=intervals[0][0] and ans[-1][1]<intervals[0][1]:\n",
    "                p=ans.pop()\n",
    "                ans.append([p[0],intervals[0][1]])\n",
    "                intervals=intervals[1:]\n",
    "            elif ans[-1][1]<intervals[0][0]:\n",
    "                ans.append(intervals[0])\n",
    "                intervals=intervals[1:]\n",
    "            else:\n",
    "                while len(intervals)>0 and ans[-1][1]>=intervals[0][1]:\n",
    "                    intervals=intervals[1:]\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort()\n",
    "        n = len(intervals)\n",
    "        \n",
    "        ans = []\n",
    "        for interval in intervals:\n",
    "            if not ans:\n",
    "                ans.append(interval)\n",
    "            if ans[-1][1] >= interval[0]:\n",
    "                ans[-1][1] = max(ans[-1][1], interval[1])\n",
    "            else:\n",
    "                ans.append(interval)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        result = []\n",
    "        if not intervals:\n",
    "            return result\n",
    "        intervals = sorted(intervals)\n",
    "        for first, second in intervals:\n",
    "            if not result or result[-1][1] < first:\n",
    "                result.append([first, second])\n",
    "            else:\n",
    "                result[-1][1] = max(result[-1][1], second)\n",
    "        return result        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals):\n",
    "        intervals1 = sorted(intervals,key = lambda x:x[0])      #按照第一列排序（二位数组）##sorted(a, key=lambda x: (x[1], x[0]))  先按第二列排序，再按第一列排序\n",
    "        print(intervals1)\n",
    "        i = 0\n",
    "        while i < len(intervals1)-1:\n",
    "            print(i)\n",
    "            if intervals1[i][1] >= intervals1[i+1][0] and intervals1[i][1] < intervals1[i+1][1]:        #合并\n",
    "                intervals1[i][1] = intervals1[i+1][1]\n",
    "                del intervals1[i+1]\n",
    "                i -= 1    \n",
    "            elif intervals1[i][1] >= intervals1[i+1][0] and intervals1[i][1] > intervals1[i+1][1]:        #\n",
    "                del intervals1[i+1]\n",
    "                i -= 1\n",
    "            elif intervals1[i][1] == intervals1[i+1][1] and intervals1[i][0] >= intervals1[i+1][0]:\n",
    "                del intervals1[i]\n",
    "                i -=1\n",
    "            elif intervals1[i][1] == intervals1[i+1][1] and intervals1[i][0] < intervals1[i+1][0]:\n",
    "                del intervals1[i+1]\n",
    "                i -= 1\n",
    "            i += 1\n",
    "        return intervals1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort(key=itemgetter(0,1))\n",
    "        res = []\n",
    "        last_interval = intervals[0]\n",
    "        for i in range(1, len(intervals)):\n",
    "            cur_interval = intervals[i]\n",
    "            if cur_interval[0] <= last_interval[1]:\n",
    "                last_interval[1] = max(last_interval[1], cur_interval[1])\n",
    "            else:\n",
    "                res.append(last_interval)\n",
    "                last_interval = cur_interval\n",
    "\n",
    "        res.append(last_interval)\n",
    "\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort()\n",
    "        ans = [intervals[0]]\n",
    "        L , R = 1 , 0\n",
    "        while L < len(intervals):\n",
    "            if ans[R][1] < intervals[L][0]:\n",
    "                ans.append(intervals[L])\n",
    "                R += 1\n",
    "                L += 1\n",
    "            else:\n",
    "                ans[R] = [ans[R][0],max(ans[R][1],intervals[L][1])]\n",
    "                L += 1\n",
    "\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        n = len(intervals)\n",
    "        intervals.sort()\n",
    "        ans = [intervals[0]]\n",
    "        for i in range(1,n):\n",
    "            if intervals[i][0] <= ans[-1][1]:\n",
    "                ans[-1][1] = max(intervals[i][1],ans[-1][1])\n",
    "            else:\n",
    "                ans.append(intervals[i])\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        merged = []\n",
    "        intervals.sort(key = lambda x : x[0])\n",
    "\n",
    "        for interval in intervals:\n",
    "            if not merged or merged[-1][1] < interval[0]:\n",
    "                merged.append(interval)\n",
    "            else:\n",
    "                merged[-1][1] = max(merged[-1][1], interval[1])\n",
    "        \n",
    "        return merged"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort(key=lambda x: x[0])\n",
    "\n",
    "        left, right = -1, -1\n",
    "        res = []\n",
    "\n",
    "        for x, y in intervals:\n",
    "            if x <= right and y > right:\n",
    "                res[-1][1] = y\n",
    "                right = y\n",
    "            elif x > right:\n",
    "                res.append([x, y])\n",
    "                left, right = x, y\n",
    "        \n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        res = []\n",
    "        intervals = sorted(intervals, key = lambda x:(x[0],x[1]))\n",
    "        # print(intervals)\n",
    "        left = intervals[0][0]\n",
    "        right = intervals[0][1]\n",
    "        for i in range(1,len(intervals)):\n",
    "            if right>= intervals[i][0]:\n",
    "                right = max(right,intervals[i][1])\n",
    "            else:\n",
    "                res.append([left,right])\n",
    "                left = intervals[i][0]\n",
    "                right = intervals[i][1]\n",
    "        res.append([left,right])\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort(key = lambda x: (x[0], x[1]))\n",
    "        res = list()\n",
    "        s, t = intervals[0][0], intervals[0][1]\n",
    "        for i in range(len(intervals)):\n",
    "            new_s, new_t = intervals[i]\n",
    "            if new_s > t:\n",
    "                res += [[s, t]]\n",
    "                s, t = new_s, new_t\n",
    "            elif new_s <= t and new_t > t:\n",
    "                t = new_t\n",
    "            elif new_s <= t and new_t <= t:\n",
    "                continue\n",
    "        res += [[s, t]]\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "def merge_intervals(ivts):\n",
    "    \"\"\"56\"\"\"\n",
    "    if len(ivts) == 1:\n",
    "        return ivts\n",
    "    ivts = sorted(ivts, key=lambda n: [n[0], n[1]])\n",
    "    res = []\n",
    "    prev = ivts[0]\n",
    "    for index in range(1, len(ivts)):\n",
    "        a, b = ivts[index]\n",
    "        pa, pb = prev\n",
    "        if a > pb:\n",
    "            res.append(prev)\n",
    "            prev = [a, b]\n",
    "        else:\n",
    "            prev = [pa, max(b, pb)]\n",
    "    res.append(prev)\n",
    "    return res\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        return merge_intervals(intervals)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort()\n",
    "        merged = []\n",
    "        for interval in intervals:\n",
    "            # 如果列表为空，或者当前区间与上一区间不重合，直接添加\n",
    "            if not merged or merged[-1][1] < interval[0]:\n",
    "                merged.append(interval)\n",
    "            else:\n",
    "                # 否则的话，我们就可以与上一区间进行合并\n",
    "                merged[-1][1] = max(merged[-1][1], interval[1])\n",
    "        return merged"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort(key = lambda x: x[0])\n",
    "        i = 0\n",
    "        while i < len(intervals) - 1:\n",
    "            if intervals[i][1] < intervals[i + 1][0]:\n",
    "                i += 1\n",
    "            else:\n",
    "                intervals[i][1] = max(intervals[i][1], intervals[i + 1][1])\n",
    "                intervals.pop(i + 1)\n",
    "        return intervals\n",
    "\n",
    "        # while i < len(intervals) - 1:\n",
    "        #     if intervals[i][1] >= intervals[i + 1][1]:\n",
    "        #         intervals.pop(i + 1)\n",
    "        #     elif intervals[i][1] >= intervals[i + 1][0]:\n",
    "        #         temp = [intervals[i][0], intervals[i + 1][1]]\n",
    "        #         intervals.pop(i)\n",
    "        #         intervals.pop(i)\n",
    "        #         intervals.insert(i, temp)\n",
    "        #     else:\n",
    "        #         i += 1\n",
    "        # return intervals\n",
    "                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort()\n",
    "        size=len(intervals)\n",
    "        i=0\n",
    "        while i<size-1:\n",
    "            if intervals[i][1]>=intervals[i+1][0]:\n",
    "                if intervals[i][1]<intervals[i+1][1]:\n",
    "\n",
    "                    intervals[i][1]=intervals[i+1][1]\n",
    "                del intervals[i+1]\n",
    "                i-=1\n",
    "                size-=1\n",
    "            \n",
    "            i+=1\n",
    "        return intervals"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        l_last = 0\n",
    "        while l_last != len(intervals):\n",
    "            l_last = len(intervals)\n",
    "            i = 0\n",
    "            while i < len(intervals):\n",
    "                p = intervals[i]\n",
    "                j = i+1\n",
    "                while j < len(intervals):\n",
    "                    q = intervals[j]\n",
    "                    if (p[1]-q[0]) * (p[0]-q[1]) <= 0:\n",
    "                        l = min(p[0], q[0])\n",
    "                        r = max(p[1], q[1])\n",
    "                        del intervals[j]\n",
    "                        intervals[i][0] = l\n",
    "                        intervals[i][1] = r \n",
    "                        j -= 1\n",
    "                    j += 1\n",
    "                i += 1\n",
    "        return intervals"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        if len(intervals) <= 1:\n",
    "            return intervals\n",
    "        results = [intervals[0]]\n",
    "        for i in range(1, len(intervals)):\n",
    "            item = intervals[i]\n",
    "            j = 0\n",
    "            while True:\n",
    "                if j >= len(results):\n",
    "                    break\n",
    "                if results[j][1] < item[0] or results[j][0] > item[1]:\n",
    "                    j += 1\n",
    "                    continue\n",
    "                else:\n",
    "                    item2 = results.pop(j)\n",
    "                    left, right = min(item[0], item2[0]), max(item[1], item2[1])\n",
    "                    item = [left, right]\n",
    "            results.append(item)\n",
    "        return results\n",
    "\n",
    "            \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort()\n",
    "        res=[]\n",
    "        t=intervals[0]\n",
    "        for i in range(1,len(intervals)):\n",
    "            if t[1]>=intervals[i][0]:\n",
    "                t=[t[0],max(t[1],intervals[i][1])]\n",
    "            else:\n",
    "                res.append(t)\n",
    "                t=intervals[i]\n",
    "        res.append(t)\n",
    "        return res\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort()\n",
    "        n = len(intervals)\n",
    "        ans, res = [], []\n",
    "        temp = [intervals[0]]\n",
    "        ma = intervals[0][1]\n",
    "        for i in range(1,n):\n",
    "            if intervals[i][0] <= ma or (intervals[i][0] <= ma and intervals[i][1] <= ma):\n",
    "                ma = max(ma,intervals[i][0],intervals[i][1])\n",
    "                temp.append(intervals[i])\n",
    "            else:\n",
    "                ans.append(temp)\n",
    "                ma = intervals[i][1]\n",
    "                temp = [intervals[i]]\n",
    "        ans.append(temp)\n",
    "        for i in range(len(ans)):\n",
    "            temp1 = ans[i]\n",
    "            start = temp1[0][0]\n",
    "            ma1 = 0\n",
    "            for j in range(len(temp1)):\n",
    "                ma1 = temp1[j][1] if temp1[j][1] > ma1 else ma1\n",
    "            res.append((start,ma1))\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort()\n",
    "        left = 0 \n",
    "        right = 1\n",
    "\n",
    "        while right < len(intervals):\n",
    "            left1, left2 = intervals[left][0], intervals[left][1]\n",
    "            right1, right2 = intervals[right][0], intervals[right][1]\n",
    "\n",
    "            if left2 < right1:\n",
    "                left += 1\n",
    "                right += 1\n",
    "            else:\n",
    "                intervals[right] = [left1, max(left2, right2)]\n",
    "                intervals.pop(left)\n",
    "\n",
    "        return intervals"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        if len(intervals)==0:\n",
    "            return intervals\n",
    "        intervals.sort(key = lambda x:x[0])\n",
    "        i = 0\n",
    "        while i < len(intervals)-1:\n",
    "            if intervals[i+1][0]<=intervals[i][1]:\n",
    "                left, right = intervals[i][0], max(intervals[i+1][1], intervals[i][1])\n",
    "                intervals.pop(i+1)\n",
    "                intervals[i] = [left, right]\n",
    "            else:\n",
    "                i+=1\n",
    "        return intervals\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals = sorted(intervals)\n",
    "        l = 0\n",
    "        r = 1\n",
    "        while r<len(intervals):\n",
    "            x1, y1 = intervals[l]\n",
    "            x2, y2 = intervals[r]\n",
    "            if y1<x2:\n",
    "                l,r = l+1, r+1\n",
    "            else:\n",
    "                intervals[r] = x1, max(y1, y2)\n",
    "                intervals.pop(l)\n",
    "        return intervals"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        if not intervals:\n",
    "            return []\n",
    "        intervals.sort(key = lambda x:x[0])\n",
    "\n",
    "        m = [intervals[0]]\n",
    "        for i in range(1, len(intervals)):\n",
    "            print(intervals[i][0], m[-1][1])\n",
    "            if intervals[i][0] <= m[-1][1]:\n",
    "                m[-1][1] = max(intervals[i][1], m[-1][1])\n",
    "            else:\n",
    "                m.append(intervals[i])\n",
    "        return m\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        intervals.sort(key = lambda x: (x[0],x[1]))\n",
    "        res = []\n",
    "\n",
    "        for inter in intervals:\n",
    "            if not res or res[-1][1] < inter[0]:\n",
    "                res.append(inter)\n",
    "            else:\n",
    "                res[-1][1] = max(res[-1][1],inter[1])\n",
    "        \n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n",
    "        res = []\n",
    "        intervals.sort(key=lambda num: num[0])\n",
    "        for s_i, e_i in intervals:\n",
    "            if res:\n",
    "                s_prev, e_prev = res[-1]\n",
    "                if s_i > e_prev:  # cannot merge\n",
    "                    res.append([s_i, e_i])\n",
    "                elif e_i < e_prev:\n",
    "                    continue\n",
    "                else:\n",
    "                    res[-1][1] = e_i\n",
    "            else:\n",
    "                res.append([s_i, e_i])\n",
    "        \n",
    "        return res\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n",
    "        if not lists:\n",
    "            return ListNode().next\n",
    "        \n",
    "        items = []\n",
    "        for _list in lists:\n",
    "            while _list:\n",
    "                items.append(_list.val)\n",
    "                _list = _list.next\n",
    "                \n",
    "            \n",
    "        items = sorted(items)\n",
    "        \n",
    "        \n",
    "        result = temp = ListNode()\n",
    "        \n",
    "        for item in items:\n",
    "            temp.next = ListNode(item)\n",
    "            temp = temp.next\n",
    "        \n",
    "        return result.next\n",
    "    \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists):\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        final_rel=[]\n",
    "        now_list=[]\n",
    "        flag=1\n",
    "        l_len=len(lists)\n",
    "        min_index=0\n",
    "        while(flag):\n",
    "            min=10000000\n",
    "            flag=0\n",
    "            for index in range(l_len):\n",
    "                if(lists[index]!=None):\n",
    "                    flag=1\n",
    "                    if(min<lists[index].val):\n",
    "                        continue\n",
    "                    else:\n",
    "                        min=lists[index].val\n",
    "                        min_index=index\n",
    "            if(flag):\n",
    "                final_rel.append(min)\n",
    "                lists[min_index]=lists[min_index].next\n",
    "        return final_rel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists):\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        lens = len(lists)\n",
    "        if not lens:\n",
    "            return []\n",
    "        elif lens == 1:\n",
    "            return lists[0]\n",
    "        else:\n",
    "            return self.devide(lists, 0, lens - 1)\n",
    "\n",
    "    def devide(self, lists, l_p, r_p):\n",
    "        if l_p == r_p:\n",
    "            return lists[l_p]\n",
    "        else:\n",
    "            mid = (l_p + r_p) // 2\n",
    "            left = self.devide(lists, l_p, mid)\n",
    "            right = self.devide(lists, mid + 1, r_p)\n",
    "            return self.merge2Lists(left, right)\n",
    "\n",
    "    def merge2Lists(self, list1, list2):\n",
    "        root = ListNode(0)\n",
    "        tmp = root\n",
    "        while list1 and list2:\n",
    "            if list1.val > list2.val:\n",
    "                tmp.next = list2\n",
    "                list2 = list2.next\n",
    "                tmp = tmp.next\n",
    "            else:\n",
    "                tmp.next = list1\n",
    "                list1 = list1.next\n",
    "                tmp = tmp.next\n",
    "        if list1:\n",
    "            tmp.next = list1\n",
    "        if list2:\n",
    "            tmp.next = list2\n",
    "        return root.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: 'List[ListNode]') -> 'ListNode':\n",
    "        from heapq import heappush, heappop, heapreplace, heapify\n",
    "        dummy = node = ListNode(0)\n",
    "        h = [(n.val, i, n) for i, n in enumerate(lists) if n]\n",
    "        # To make sure this runs in Python3, simply add a tie-breaker in your heap elements (tuples). This assures that the heapq algo will never compare two variables of type ListNode.\n",
    "        heapify(h)\n",
    "        while h:\n",
    "            v, i, n = h[0]\n",
    "            if n.next is None:\n",
    "                heappop(h)\n",
    "            else:\n",
    "                heapreplace(h, (n.next.val, i, n.next))\n",
    "            node.next = n\n",
    "            node = node.next\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists):\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        res = []\n",
    "        for i in range(len(lists)):\n",
    "            item = lists[i]\n",
    "            while item != None:\n",
    "                res.append(item.val)\n",
    "                item = item.next\n",
    "        res = sorted(res)\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    import heapq\n",
    "    def mergeKLists(self, lists):\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        ret,heap=[],[]\n",
    "        \n",
    "        for lst in lists:\n",
    "            while lst:\n",
    "            \n",
    "                heapq.heappush(heap,lst.val)\n",
    "\n",
    "                lst=lst.next\n",
    "            \n",
    "        while heap:\n",
    "            ret.append(heapq.heappop(heap))\n",
    "        \n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n",
    "        a=[]\n",
    "        for i in range(len(lists)):\n",
    "            # b=lists[i]\n",
    "            while lists[i]:\n",
    "                a.append(lists[i].val)\n",
    "                lists[i]=lists[i].next\n",
    "        a.sort()\n",
    "        return a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists):\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        nodes = []\n",
    "        cur = head = ListNode(0)\n",
    "        for l in lists:\n",
    "            \n",
    "            while l:\n",
    "                nodes.append(l.val)\n",
    "                l = l.next\n",
    "        for x in sorted(nodes):\n",
    "            cur.next = ListNode(x)\n",
    "            cur = cur.next\n",
    "        \n",
    "        return head.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists):\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        elems = []\n",
    "        for p in lists:\n",
    "            while p:\n",
    "                elems.append(p.val)\n",
    "                p = p.next\n",
    "        elems.sort()\n",
    "        \n",
    "        dummy = helper = ListNode(0)\n",
    "        for elem in elems:\n",
    "            helper.next = ListNode(elem)\n",
    "            helper = helper.next\n",
    "        \n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists):\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        lists = list(filter(lambda ll: ll is not None, lists))\n",
    "        if lists is None or len(lists) == 0:\n",
    "            return None\n",
    "        result_head = ListNode(-1)\n",
    "        pointers = [head for head in lists]\n",
    "        min_value = pointers[0].val\n",
    "        main_pointer = result_head\n",
    "        min_index = 0\n",
    "        len_pointer = len(pointers)\n",
    "        while min_value is not None:\n",
    "            for i in range(len_pointer):\n",
    "                pointer = pointers[i]\n",
    "                if pointer is None:\n",
    "                    continue\n",
    "                if pointer.val <= min_value:\n",
    "                    min_value = pointer.val\n",
    "                    min_index = i\n",
    "            main_pointer.next = ListNode(min_value)\n",
    "            main_pointer = main_pointer.next\n",
    "            pointers[min_index] = pointers[min_index].next\n",
    "            min_value = None\n",
    "            for i in range(len_pointer):\n",
    "                pointer = pointers[i]\n",
    "                if pointer is not None:\n",
    "                    min_value = pointer.val\n",
    "                    break\n",
    "        return result_head.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "from queue import PriorityQueue\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists):\n",
    "        head = p = ListNode(0)\n",
    "        n = 1\n",
    "        q = PriorityQueue()\n",
    "\n",
    "        for l in lists:\n",
    "            if l:\n",
    "                q.put((l.val, n, l))\n",
    "                n += 1 \n",
    "\n",
    "        while not q.empty():\n",
    "            val, m, node = q.get()\n",
    "            p.next = ListNode(val)\n",
    "            p = p.next\n",
    "            node = node.next #关键\n",
    "            if node:\n",
    "                q.put((node.val, n, node))\n",
    "                n += 1\n",
    "        \n",
    "        return head.next\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "    mn*log(m)  m是链表上限个数　n是长度上限\n",
    "    假设m条长度为n的做合并，m路归并问题　最快的办法是两两归并\n",
    "    第一轮: m/2组 归并过程将两个链表分别遍历一次　2n　　　　　　第一轮:m*n\n",
    "    第二轮: m/4组*4n=mn\n",
    "    ...\n",
    "    总共log(m)轮　　故时间复杂度为mn*log(m)\n",
    "\"\"\"\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: 'List[ListNode]') -> 'ListNode':\n",
    "        m = len(lists)\n",
    "        if(m==1):\n",
    "            return lists[0]\n",
    "        if(m==0):\n",
    "            return None\n",
    "        print ('链表个数为',m)\n",
    "        for i in range(m//2):\n",
    "            pre = lists[2*i] #插入位置\n",
    "            b = lists[2*i+1]\n",
    "            if(pre==None):\n",
    "                lists[2*i]=b\n",
    "                continue\n",
    "            \n",
    "            if(b==None):\n",
    "                continue\n",
    "            # 如果第二个链首元素小于第一个　则更换链首\n",
    "            if(b.val<pre.val):\n",
    "                c = b.next\n",
    "                b.next = pre\n",
    "                lists[2*i] = b\n",
    "                b = c\n",
    "            pre = lists[2*i]    \n",
    "            a = pre.next  #当前被比较值\n",
    "            \n",
    "            while (b!=None):               \n",
    "                while(a!=None and b.val>a.val):\n",
    "                    pre = a\n",
    "                    a = a.next\n",
    "                if(a==None):\n",
    "                    pre.next = b\n",
    "                    break\n",
    "                #找到插入位置\n",
    "                pre.next = b\n",
    "                c = b.next\n",
    "                if(c==None):\n",
    "                    d = b\n",
    "                b.next = a\n",
    "                pre = b\n",
    "                b = c\n",
    "                #print(pre.val,a.val,b.val)\n",
    "\n",
    "            pre = lists[2*i]\n",
    "            while(pre!=None):\n",
    "                print(pre.val,end='')\n",
    "                pre=pre.next\n",
    "            #print()\n",
    "        print ('    链表个数为',len(lists))\n",
    "        for i in range(m//2):\n",
    "            lists.remove(lists[2*i+1-i])\n",
    "            print('移除',2*i+1)\n",
    "\n",
    "        \n",
    "        return self.mergeKLists(lists)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists):\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        res = None\n",
    "        if not lists:\n",
    "            return res\n",
    "        d={}\n",
    "        reslist = []\n",
    "        for i in range(len(lists)):\n",
    "            d[i]=[]\n",
    "            node = lists[i]\n",
    "            while node:\n",
    "                d[i].append(node.val)\n",
    "                node = node.next\n",
    "            reslist += d[i]\n",
    "            reslist.sort()\n",
    "        if not reslist:\n",
    "            return res\n",
    "        else:\n",
    "            \n",
    "            for n in reslist:\n",
    "                if not res:\n",
    "                    res = ListNode(n)\n",
    "                    upnode = res\n",
    "                else:\n",
    "                    node = ListNode(n)\n",
    "                    upnode.next = node\n",
    "                    upnode = upnode.next\n",
    "            return res\n",
    "        \n",
    "            \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode(object):\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution(object):\n",
    "    def mergeKLists(self, lists):\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        tmp=[]\n",
    "        for i in lists:\n",
    "            if i not in tmp and i!=None:\n",
    "                tmp.append(i)\n",
    "        if not tmp:\n",
    "            return\n",
    "        ans=ListNode(None)\n",
    "            \n",
    "        p=ans\n",
    "        listval=[]\n",
    "        listnum=[]\n",
    "        lists=tmp\n",
    "        for i in range(len(lists)):\n",
    "            listval.append(lists[i].val)\n",
    "            listnum.append(i)\n",
    "        Z=zip(listval,listnum)\n",
    "        Z=sorted(Z)\n",
    "        listval,listnum=zip(*Z)\n",
    "        listval,listnum=list(listval),list(listnum)\n",
    "        while listval:\n",
    "            p.next=ListNode(listval[0])\n",
    "            p=p.next\n",
    "            if lists[listnum[0]].next:\n",
    "                tmp=lists[listnum[0]].next.val\n",
    "                lists[listnum[0]]=lists[listnum[0]].next\n",
    "                num=listnum[0]\n",
    "                del listval[0]\n",
    "                del listnum[0]\n",
    "                if listval:\n",
    "                    if tmp<=listval[0]:\n",
    "                        listval.insert(0,tmp)\n",
    "                        listnum.insert(0,num)\n",
    "                    elif tmp>=listval[-1]:\n",
    "                        listval.append(tmp)\n",
    "                        listnum.append(num)\n",
    "                    else:\n",
    "                        for i in range(len(listval)):\n",
    "                            if listval[i]>=tmp:\n",
    "                                break\n",
    "                        listval.insert(i,tmp)\n",
    "                        listnum.insert(i,num)\n",
    "                else:\n",
    "                    listval.append(tmp)\n",
    "                    listnum.append(num)\n",
    "                    \n",
    "            else:\n",
    "                del listval[0]\n",
    "                del listnum[0]\n",
    "        return ans.next\n",
    "            \n",
    "        \n",
    "            \n",
    "        \n",
    "        \n",
    "            \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "class Node:\n",
    "    def __init__(self, node):\n",
    "        self.val = node.val\n",
    "        self.next = None\n",
    "        \n",
    "    def __lt__(self, a):\n",
    "        return self.val < a.val\n",
    "\n",
    "def node(head):\n",
    "    if head is None:\n",
    "        return None\n",
    "    else:\n",
    "        nhead = Node(head)\n",
    "        nhead.next = node(head.next)\n",
    "        return nhead\n",
    "\n",
    "class Solution:\n",
    "    \n",
    "    def mergeKLists(self, lists):\n",
    "        \"\"\"\n",
    "        :type lists: List[ListNode]\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        lists = [i for i in lists if i is not None]\n",
    "        if len(lists) == 0:\n",
    "            return None\n",
    "        ans = ListNode(0)\n",
    "        p = ans\n",
    "        lists = [node(i) for i in lists]\n",
    "        heap = [i for i in lists]\n",
    "        import heapq\n",
    "        heapq.heapify(heap)\n",
    "        while len(heap) > 0:\n",
    "            n = heapq.heappop(heap)\n",
    "            p.next = ListNode(n.val)\n",
    "            p = p.next\n",
    "            if n.next is not None:\n",
    "                heapq.heappush(heap, n.next)\n",
    "        return ans.next\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n",
    "        if len(lists) == 0:\n",
    "            return None\n",
    "        if len(lists) == 1:\n",
    "            return lists[0]\n",
    "        # num = 0\n",
    "        # for item in lists:\n",
    "        #     if item is None:\n",
    "        #         num += 1\n",
    "        # if num == len(lists):\n",
    "        #     return None\n",
    "        result = lists[0]\n",
    "        for i in range(len(lists)):\n",
    "            if i > 0:\n",
    "                result = self.merge2lists(result, lists[i])\n",
    "        return result\n",
    "\n",
    "    def merge2lists(self, l1: list, l2: list) -> ListNode:\n",
    "        head = ListNode(0)\n",
    "        start = head\n",
    "        while l1 and l2:\n",
    "            if l1.val < l2.val:\n",
    "                start.next = l1\n",
    "                l1 = l1.next\n",
    "            else:\n",
    "                start.next = l2\n",
    "                l2 = l2.next\n",
    "            start = start.next\n",
    "        if l1:\n",
    "            start.next = l1\n",
    "        if l2:\n",
    "            start.next = l2\n",
    "        if start.next is None:\n",
    "            return None\n",
    "        return head.next\n",
    "\n",
    "\n",
    "    \n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "import heapq\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n",
    "        #lists[i].val打印的是lists中第i个list的第一个节点的值\n",
    "        l,size=[],len(lists)\n",
    "        for i in range(size):\n",
    "            if lists[i]:\n",
    "                heapq.heappush(l,(lists[i].val,i))\n",
    "        dummy=ListNode(0)\n",
    "        cur=dummy\n",
    "        while l:\n",
    "            _,index=heapq.heappop(l)\n",
    "            head=lists[index]\n",
    "            cur.next=head\n",
    "            cur=cur.next\n",
    "            if head.next:\n",
    "                heapq.heappush(l,(head.next.val,index))\n",
    "                lists[index]=head.next\n",
    "                head.next=None\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n",
    "        if not lists:\n",
    "            return\n",
    "        if len(lists)==1:\n",
    "            return lists[0]\n",
    "\n",
    "        def mergeTwoLists(l1, l2):\n",
    "            if not l1 and not l2:\n",
    "                return \n",
    "            if not l1:\n",
    "                return l2\n",
    "            if not l2:\n",
    "                return l1\n",
    "            cur1=l1\n",
    "            cur2=l2\n",
    "            helpcur=ListNode(1)\n",
    "            start=helpcur\n",
    "            while cur1 and cur2:\n",
    "                if cur1.val<=cur2.val:\n",
    "                    helpcur.next=cur1\n",
    "                    cur1=cur1.next\n",
    "                else:\n",
    "                    helpcur.next=cur2\n",
    "                    cur2=cur2.next\n",
    "                helpcur=helpcur.next\n",
    "            if cur1:\n",
    "                helpcur.next=cur1\n",
    "            elif cur2:\n",
    "                helpcur.next=cur2\n",
    "            return start.next\n",
    "        i=1\n",
    "        cur=lists[i-1]\n",
    "        while i<len(lists):\n",
    "            cur=mergeTwoLists(cur,lists[i])\n",
    "            i+=1\n",
    "        return cur\n",
    "       \n",
    "\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import heapq\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n",
    "        ans = cur = ListNode()\n",
    "        heap = []\n",
    "        heapq.heapify(heap)\n",
    "        for i in range(len(lists)):\n",
    "            if lists[i]:\n",
    "                heapq.heappush(heap, (lists[i].val, i))\n",
    "                lists[i] = lists[i].next\n",
    "        \n",
    "        while heap:\n",
    "            val, idx = heapq.heappop(heap)\n",
    "            node = ListNode(val)\n",
    "            cur.next = node\n",
    "            cur = cur.next\n",
    "            if lists[idx] != None:\n",
    "                heapq.heappush(heap, (lists[idx].val, idx))\n",
    "                lists[idx] = lists[idx].next\n",
    "        return ans.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        if len(lists) == 0:\n",
    "            return None\n",
    "        if len(lists) == 1 and lists[0]:\n",
    "            return lists[0]\n",
    "        # l1 = lists[:len(lists)//2]\n",
    "        # l2 = lists[len(lists)//2:]\n",
    "        # print(l1,l2)\n",
    "        # res = self.func(l1,l2)\n",
    "        \n",
    "        # for link in lists:\n",
    "        #     if link is None:\n",
    "        #         continue\n",
    "        #     else:\n",
    "        #         res = self.merge(res, link)\n",
    "        return self.func(lists)\n",
    "    \n",
    "    def func(self, lists):\n",
    "        res = None\n",
    "        if len(lists) < 4:\n",
    "            for link in lists:\n",
    "                if link is None:\n",
    "                    continue\n",
    "                else:\n",
    "                    res = self.merge(res, link)\n",
    "        else:\n",
    "            l1 = lists[:len(lists)//2]\n",
    "            l2 = lists[len(lists)//2:]\n",
    "            m1 = self.func(l1)\n",
    "            m2 = self.func(l2)\n",
    "            res = self.merge(m1, m2)\n",
    "        return res\n",
    "\n",
    "\n",
    "    def merge(self, p1, p2):\n",
    "        res = ListNode()\n",
    "        p = res\n",
    "        if p1 is None:\n",
    "            return p2\n",
    "        elif p2 is None:\n",
    "            return p1\n",
    "        while p1 is not None and p2 is not None:\n",
    "            if p1.val <= p2.val:\n",
    "                p.next = p1\n",
    "                p1 = p1.next\n",
    "            else:\n",
    "                p.next = p2\n",
    "                p2 = p2.next\n",
    "            p = p.next\n",
    "            if p1 is None:\n",
    "                p.next = p2\n",
    "            elif p2 is None:\n",
    "                p.next = p1\n",
    "        # print(\"merge!!!\",res.next)\n",
    "        return res.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        stack=[]\n",
    "        for i in lists:\n",
    "            while i:\n",
    "                stack.append(i)\n",
    "                i=i.next\n",
    "        stack.sort(key=lambda x:x.val)\n",
    "        for i in range(len(stack)-1):\n",
    "            stack[i].next=stack[i+1]\n",
    "        if stack==[]:\n",
    "            return\n",
    "        return stack[0]\n",
    "\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        interval = 1\n",
    "        n = len(lists)\n",
    "        while interval < n:\n",
    "            for i in range(0, n - interval, interval * 2):\n",
    "                lists[i] = self._merge(lists[i], lists[i + interval])\n",
    "            interval *= 2\n",
    "        return lists[0] if lists else None\n",
    "\n",
    "    def _merge(self, l1, l2):\n",
    "        dummy = l = ListNode(None)\n",
    "        while l1 and l2:\n",
    "            if l1.val < l2.val:\n",
    "                l.next = l1\n",
    "                l1 = l1.next\n",
    "            else:\n",
    "                l.next = l2\n",
    "                l2 = l2.next\n",
    "            l = l.next\n",
    "        l.next = l1 or l2\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "\n",
    "        head = ListNode(None)\n",
    "        start_node = head\n",
    "        while lists:\n",
    "            cur_min = None\n",
    "            min_node_index = None\n",
    "            index = 0\n",
    "            while index<len(lists):\n",
    "                if not lists[index]:\n",
    "                    lists.pop(index)\n",
    "                    continue\n",
    "                if (cur_min is None) or (cur_min>lists[index].val):\n",
    "                    cur_min = lists[index].val\n",
    "                    min_node_index = index\n",
    "                # print(start_node)\n",
    "                index +=1\n",
    "\n",
    "            if not lists:\n",
    "                break\n",
    "            start_node.next = lists.pop(min_node_index)\n",
    "            start_node = start_node.next\n",
    "            lists.append(start_node.next)\n",
    "\n",
    "        return head.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "\n",
    "        def get_two_merge(list1, list2):\n",
    "            l1, l2, l = list1, list2, ListNode()\n",
    "            node = l\n",
    "\n",
    "            while l1 and l2:\n",
    "                if l1.val < l2.val:\n",
    "                    l.next = l1\n",
    "                    l1 = l1.next\n",
    "                else:\n",
    "                    l.next = l2\n",
    "                    l2 = l2.next\n",
    "                l = l.next\n",
    "\n",
    "            if l1:\n",
    "                l.next = l1\n",
    "            if l2:\n",
    "                l.next = l2\n",
    "            \n",
    "            return node.next\n",
    "        \n",
    "        n = len(lists)\n",
    "        if n == 0:\n",
    "            return ListNode().next\n",
    "        ans = lists[0]\n",
    "        for i in range(1, n):\n",
    "            another = lists[i]\n",
    "            ans = get_two_merge(ans, another)\n",
    "        return ans   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        head = ListNode()\n",
    "        cur = head\n",
    "        while True:\n",
    "            min_val = float('inf')\n",
    "            min_index = -1\n",
    "            for i in range(len(lists)):\n",
    "                if lists[i] and lists[i].val < min_val:\n",
    "                    min_val = lists[i].val\n",
    "                    min_index = i\n",
    "            if min_index == -1:\n",
    "                break\n",
    "            cur.next = lists[min_index]\n",
    "            cur = cur.next\n",
    "            lists[min_index] = lists[min_index].next\n",
    "        return head.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        n = len(lists)\n",
    "        first_list = []\n",
    "\n",
    "        for i in range(n):\n",
    "            if lists[i] != None and lists[i].val != None:\n",
    "                first_list += [(lists[i].val, i)]\n",
    "        heapify(first_list)\n",
    "         \n",
    "        result = ListNode()\n",
    "        ans = result\n",
    "        while len(first_list) > 0:\n",
    "            num, sequence = heappop(first_list)\n",
    "            lists[sequence] = lists[sequence].next\n",
    "            result.next = ListNode(num)\n",
    "            result = result.next\n",
    "\n",
    "            if lists[sequence] != None:\n",
    "                heappush(first_list, (lists[sequence].val, sequence))\n",
    "\n",
    "        return ans.next\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        #使用一个队列存储\n",
    "\n",
    "        heap=[]\n",
    "\n",
    "        for sub_list in lists:\n",
    "\n",
    "            while sub_list:\n",
    "\n",
    "                heap.append(sub_list.val)\n",
    "\n",
    "                sub_list=sub_list.next\n",
    "\n",
    "        #对heapify进行堆排序\n",
    "\n",
    "        import heapq\n",
    "\n",
    "        heapq.heapify(heap)\n",
    "\n",
    "        print(heap)\n",
    "\n",
    "        #heap.sort(reverse=True)\n",
    "\n",
    "        head=ListNode(None)\n",
    "\n",
    "        curr_list=head\n",
    "\n",
    "        while heap:\n",
    "\n",
    "            temp_list=ListNode(heapq.heappop(heap))\n",
    "\n",
    "            curr_list.next=temp_list\n",
    "\n",
    "            curr_list=curr_list.next\n",
    "\n",
    "        return head.next\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "import heapq\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        heap = []\n",
    "        heapq.heapify(heap)\n",
    "        dumb = cur = ListNode()\n",
    "        for i, l in enumerate(lists):\n",
    "            if l:\n",
    "                heapq.heappush(heap, (l.val, i))\n",
    "        while heap:\n",
    "            val, i = heapq.heappop(heap)\n",
    "            cur.next = ListNode(val)\n",
    "            cur = cur.next\n",
    "            if lists[i].next:\n",
    "                lists[i] = lists[i].next\n",
    "                heapq.heappush(heap, (lists[i].val, i))\n",
    "        return dumb.next\n",
    "\n",
    "\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "\n",
    "        if not lists:return None\n",
    "\n",
    "        # 清理没有元素的链表\n",
    "        lists = [i for i in lists if i]\n",
    "\n",
    "        n  = len(lists)\n",
    "        if n == 0:return None\n",
    "\n",
    "        # 以头节点元素最小的链表为基准\n",
    "        # firstnodelist = [(i,i.val) for i in lists]\n",
    "        firstnodelist = [(i,lists[i].val) for i in range(n)]\n",
    "        minI , minV = min(firstnodelist , key = lambda x:x[1])\n",
    "\n",
    "        res = lists[minI]\n",
    "        lists.pop(minI)\n",
    "\n",
    "        pointer = res\n",
    "\n",
    "        while lists:\n",
    "\n",
    "            length = len(lists)\n",
    "\n",
    "            # 找到当前小于基准节点下一个节点的最小节点\n",
    "            firstnodelist = [(i,lists[i].val) for i in range(length)]\n",
    "            minI , minV = min(firstnodelist , key = lambda x:x[1])\n",
    "\n",
    "            # 当前基准节点有下一个节点\n",
    "            if pointer.next:\n",
    "\n",
    "                # 基准节点下一个的值大于选中的，执行插入\n",
    "                if minV < pointer.next.val:\n",
    "                    # 获取一个待插入节点的拷贝\n",
    "                    toInsert = lists[minI]\n",
    "                    lists[minI] = lists[minI].next\n",
    "                    toInsert.next =  pointer.next\n",
    "                    pointer.next = toInsert\n",
    "                    pointer = pointer.next\n",
    "\n",
    "                #下一个较小，不执行动作\n",
    "                else:\n",
    "                    pointer = pointer.next\n",
    "\n",
    "            # 当前基准节点没有下一个节点,直接插入\n",
    "            else:\n",
    "                 # 获取一个待插入节点的拷贝\n",
    "                toInsert = lists[minI]\n",
    "                lists[minI] = lists[minI].next\n",
    "                toInsert.next =  pointer.next\n",
    "                pointer.next = toInsert\n",
    "                pointer = pointer.next\n",
    "\n",
    "\n",
    "            # 清理没有元素的链表\n",
    "            lists = [i for i in lists if i]\n",
    "\n",
    "\n",
    "        return res\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def have_traversed_all(self, listNodes):\n",
    "        for listNode in listNodes:\n",
    "            if listNode is not None:\n",
    "                return False \n",
    "        return True\n",
    "\n",
    "    def min_node(self, listNodes):\n",
    "        min_node = (float(\"inf\"), -1)\n",
    "        for i, listNode in enumerate(listNodes):\n",
    "            # return idx of the node with the smallest node \n",
    "            if listNode and listNode.val < min_node[0]:\n",
    "                min_node = (listNode.val, i)\n",
    "        return min_node[1]\n",
    "\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        # initialize a list of length k, with each element being the current node in each linked list that we are traversing to \n",
    "        curr_nodes = lists \n",
    "        start = ListNode()\n",
    "        curr = start\n",
    "        print(\"curr_nodes\", curr_nodes)\n",
    "        # while we haven't traversed through all the linked list:\n",
    "        while self.have_traversed_all(curr_nodes) == False:\n",
    "            # add the min of the k nodes to the returning linked list \n",
    "            min_node_idx = self.min_node(curr_nodes)\n",
    "            print(\"min_node_idx\", min_node_idx)\n",
    "            # update the node in the curr_nodes\n",
    "            curr.next = curr_nodes[min_node_idx]\n",
    "            curr = curr.next\n",
    "            curr_nodes[min_node_idx] = curr_nodes[min_node_idx].next\n",
    "            print(\"curr\", curr.val) \n",
    "        return start.next \n",
    "\n",
    "\"\"\"\n",
    "Optimizations:\n",
    "- For min_node, keep track of the min, and everytime we add to curr_nodes, we just compare with the min \n",
    "- \n",
    "\"\"\"\n",
    "\n",
    "# problems identified in the interview:\n",
    "# when there is a bug in the code, I don't understand my code, I need a way to quickly visualize what is happening and understand the bug \n",
    "# I need to practice doing print debugging \n",
    "\n",
    "# debugging strategies \n",
    "# always print \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        def merge(lists, left, right):\n",
    "            if not lists:\n",
    "                return \n",
    "            if left == right:\n",
    "                return lists[left]\n",
    "            if left > right:\n",
    "                return \n",
    "            mid = (left + right) //2 \n",
    "            return mergeSort(merge(lists, left, mid), merge(lists, mid+1, right))\n",
    "        def mergeSort(left, right):\n",
    "            cur = ListNode()\n",
    "            pre = cur \n",
    "            while left and right:\n",
    "                if left.val < right.val:\n",
    "                    new_node = ListNode(left.val)\n",
    "                    pre.next = new_node \n",
    "                    pre = pre.next \n",
    "                    left = left.next \n",
    "                else:\n",
    "                    new_node = ListNode(right.val)\n",
    "                    pre.next = new_node \n",
    "                    pre = pre.next \n",
    "                    right = right.next \n",
    "            if left:\n",
    "                pre.next = left \n",
    "            if right:\n",
    "                pre.next = right \n",
    "            return cur.next \n",
    "        return merge(lists, 0, len(lists)-1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        # while循环，两两分组归并\n",
    "        return self.merge_k_list(lists, 0, len(lists))\n",
    "    \n",
    "    def merge_k_list(self, lists, left, right):\n",
    "        if left == right:\n",
    "            return None\n",
    "        if left + 1 == right:\n",
    "            return lists[left]\n",
    "\n",
    "        mid = (left+right)//2\n",
    "        left_sort_result = self.merge_k_list(lists, left, mid)\n",
    "        right_sort_result = self.merge_k_list(lists, mid, right)\n",
    "\n",
    "        return self.merge(left_sort_result, right_sort_result)\n",
    "    \n",
    "    def merge(self, left, right):\n",
    "        dummy_head = ListNode(0, None)\n",
    "        c_node = dummy_head\n",
    "\n",
    "        while(left is not None and right is not None):\n",
    "            if left.val < right.val:\n",
    "                c_node.next = ListNode(left.val, None)\n",
    "                left = left.next\n",
    "            else:\n",
    "                c_node.next = ListNode(right.val, None)\n",
    "                right = right.next\n",
    "            c_node = c_node.next\n",
    "        \n",
    "        if left is not None:\n",
    "            c_node.next = left\n",
    "        if right is not None:\n",
    "            c_node.next = right\n",
    "        \n",
    "        return dummy_head.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class NodeIter:\n",
    "    def __init__(self,head):\n",
    "        self.p=ListNode(next=head)\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "    def __next__(self):\n",
    "        self.p=self.p.next\n",
    "        if not self.p:\n",
    "            raise StopIteration\n",
    "        return self.p\n",
    "class Solution:\n",
    "    import heapq\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        ll=[]\n",
    "        for li in lists:\n",
    "            ll.append(NodeIter(li))\n",
    "        it=heapq.merge(*ll, key=attrgetter('val'))\n",
    "        h=ListNode()\n",
    "        last=h\n",
    "        for i in it:\n",
    "            last.next=i\n",
    "            last=i\n",
    "        last.net=None\n",
    "        return h.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "      \"\"\"\n",
    "      1. 小顶堆\n",
    "      \"\"\"\n",
    "      # if not lists:\n",
    "      #   return lists\n",
    "      \n",
    "      from heapq import heappush, heappop\n",
    "      hq = []\n",
    "      dic = {}\n",
    "      \n",
    "      # initialize heap\n",
    "      for i, link in enumerate(lists):\n",
    "        if not link:\n",
    "          continue\n",
    "        print(i, link)\n",
    "        dic[f\"{i}_0\"] = link\n",
    "        heappush(hq, [link.val, f\"{i}_0\"])\n",
    "      # print(dic)\n",
    "\n",
    "      thead = ListNode()\n",
    "      head = thead\n",
    "      while hq:\n",
    "        [cur_min_val, position] = heappop(hq)\n",
    "        # create node\n",
    "        temp = ListNode(cur_min_val)\n",
    "        head.next = temp\n",
    "        head = head.next\n",
    "\n",
    "        if dic[position].next:\n",
    "          next_index = f\"{position.split('_')[0]}_{int(position.split('_')[1])+1}\"\n",
    "          dic[next_index] = dic[position].next\n",
    "          heappush(hq, [dic[position].next.val, next_index])\n",
    "\n",
    "      return thead.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class SkipListNode: \n",
    "\n",
    "\tdef __init__(self): \n",
    "\t\tself.prev = None \n",
    "\t\tself.next = None \n",
    "\t\tself.index = None \n",
    "\t\tself.up = None\n",
    "\t\tself.pv = None \n",
    "\t\n",
    "class SkipList: \n",
    "\n",
    "\tdef __init__(self): \n",
    "\t\tself.__multiple = True\n",
    "\t\tself.__reset() \n",
    "\n",
    "\tdef __reset(self): \n",
    "\t\tself.__size = 0 \n",
    "\t\tself.__head_node_list = [] \n",
    "\t\tself.__tail_node_list = [] \n",
    "\t\tnode = SkipListNode() \n",
    "\t\tself.__head_node_list.append(node) \n",
    "\t\tself.__tail_node_list.append(node) \n",
    "\n",
    "\tdef __need_add(self): \n",
    "\t\treturn 0 == random.randint(0, 3) \n",
    "\n",
    "\tdef clear(self): \n",
    "\t\tself.__reset()\n",
    "\n",
    "\tdef __insert_node(self, prev, pv, deep):\n",
    "\t\tnode = SkipListNode()\n",
    "\t\tnode.pv = pv\n",
    "\t\tif None != prev.next:\n",
    "\t\t\tprev.next.prev = node\n",
    "\t\t\tnode.next = prev.next\n",
    "\t\telse:\n",
    "\t\t\tself.__tail_node_list[deep] = node\n",
    "\t\tprev.next = node\n",
    "\t\tnode.prev = prev\n",
    "\t\treturn node\n",
    "\n",
    "\tdef __insert_deep(self, prev, deep, pv):\n",
    "\t\t#for node=prev; None!=node; node=node.next:\n",
    "\t\tnode = prev\n",
    "\t\twhile None != node:\n",
    "\t\t\tif not self.__multiple and None != node.next and pv == node.next.pv:\n",
    "\t\t\t\treturn None\n",
    "\t\t\tif None == node.next or pv < node.next.pv:\n",
    "\t\t\t\tif deep > 0:\n",
    "\t\t\t\t\taddnode = self.__insert_deep(node.index, deep - 1, pv)\n",
    "\t\t\t\t\tindexnode = None\n",
    "\t\t\t\t\tif None != addnode and self.__need_add():\n",
    "\t\t\t\t\t\tindexnode = self.__insert_node(node, pv, deep)\n",
    "\t\t\t\t\t\tindexnode.index = addnode\n",
    "\t\t\t\t\t\taddnode.up = indexnode\n",
    "\t\t\t\t\treturn indexnode\n",
    "\t\t\t\telse:\n",
    "\t\t\t\t\taddnode = self.__insert_node(node, pv, deep)\n",
    "\t\t\t\t\tif None != addnode:\n",
    "\t\t\t\t\t\tself.__size = self.__size + 1\n",
    "\t\t\t\t\treturn addnode\n",
    "\t\t\tnode = node.next\n",
    "\t\treturn None\n",
    "\t\n",
    "\tdef insert(self, pv):\n",
    "\t\taddnode = self.__insert_deep(self.__head_node_list[len(self.__head_node_list) - 1],\n",
    "\t\t\t\t\t\t\t\t\t\tlen(self.__head_node_list) - 1, pv)\n",
    "\t\tif None != addnode and self.__need_add() and len(self.__head_node_list) < 32:\n",
    "\t\t\theadnode = SkipListNode()\n",
    "\t\t\theadnode.index = self.__head_node_list[len(self.__head_node_list)-1]\n",
    "\t\t\tself.__head_node_list[len(self.__head_node_list)-1].up = headnode\n",
    "\t\t\tself.__head_node_list.append(headnode)\n",
    "\t\t\tself.__tail_node_list.append(headnode)\n",
    "\t\t\tindexnode = self.__insert_node(headnode, pv, len(self.__head_node_list)-1)\n",
    "\t\t\tindexnode.index = addnode\n",
    "\t\t\taddnode.up = indexnode\n",
    "\t\t\t#addnode = indexnode\n",
    "\t\n",
    "\tdef __find_deep(self, prev, pv):\n",
    "\t\tnode = prev\n",
    "\t\twhile None != node:\n",
    "\t\t\tif None != node.prev and pv == node.pv:\n",
    "\t\t\t\tindexnode = node\n",
    "\t\t\t\twhile None != indexnode.index:\n",
    "\t\t\t\t\tindexnode = indexnode.index\n",
    "\t\t\t\treturn indexnode\n",
    "\t\t\tif None == node.next or pv < node.next.pv:\n",
    "\t\t\t\treturn self.__find_deep(node.index, pv)\n",
    "\t\t\tnode = node.next\n",
    "\t\treturn None\n",
    "\t\n",
    "\tdef find(self, pv):\n",
    "\t\treturn self.__find_deep(self.__head_node_list[len(self.__head_node_list) - 1], pv)\n",
    "\n",
    "\tdef __erase_deep(self, prev, deep, pv):\n",
    "\t\tnode = prev\n",
    "\t\twhile None != node:\n",
    "\t\t\tif None != node.prev and pv == node.pv:\n",
    "\t\t\t\tindexnode = node\n",
    "\t\t\t\twhile None != indexnode:\n",
    "\t\t\t\t\tindexnode.prev.next = indexnode.next\n",
    "\t\t\t\t\tif None != indexnode.next:\n",
    "\t\t\t\t\t\tindexnode.next.prev = indexnode.prev\n",
    "\t\t\t\t\telse:\n",
    "\t\t\t\t\t\tself.__tail_node_list[deep] = indexnode.prev\n",
    "\t\t\t\t\tindexnode = indexnode.index\n",
    "\t\t\t\t\tdeep = deep - 1\n",
    "\t\t\t\tself.__size = self.__size - 1\n",
    "\t\t\t\treturn True\n",
    "\t\t\tif None == node.next or pv < node.next.pv:\n",
    "\t\t\t\tif deep > 0:\n",
    "\t\t\t\t\treturn self.__erase_deep(node.index, deep - 1, pv)\n",
    "\t\t\t\telse:\n",
    "\t\t\t\t\tbreak\n",
    "\t\t\tnode = node.next\n",
    "\t\treturn False\n",
    "\n",
    "\tdef erase(self, pv):\n",
    "\t\treturn self.__erase_deep(self.__head_node_list[len(self.__head_node_list) - 1], len(self.__head_node_list) - 1, pv)\n",
    "\t\n",
    "\tdef erase_node(self, node):\n",
    "\t\tif None != node.index:\n",
    "\t\t\treturn False\n",
    "\t\tdeep = 0\n",
    "\t\twhile None != node:\n",
    "\t\t\tnode.prev.next = node.next\n",
    "\t\t\tif None != node.next:\n",
    "\t\t\t\tnode.next.prev = node.prev\n",
    "\t\t\telse:\n",
    "\t\t\t\tself.__tail_node_list[deep] = node.prev\n",
    "\t\t\tnode = node.up\n",
    "\t\t\tdeep = deep + 1\n",
    "\t\tself.__size = self.__size - 1\n",
    "\t\treturn True\n",
    "\n",
    "\tdef size(self):\n",
    "\t\treturn self.__size\n",
    "\n",
    "\tdef begin(self):\n",
    "\t\treturn self.__head_node_list[0].next\n",
    "\n",
    "\tdef rbegin(self):\n",
    "\t\treturn self.__tail_node_list[0]\n",
    "\n",
    "\tdef max_deep(self):\n",
    "\t\treturn len(self.__head_node_list)\n",
    "\n",
    "class ListNode:\n",
    "    def __init__(self, val=0, next=None):\n",
    "        self.val = val\n",
    "        self.next = next\n",
    "\n",
    "class HeadNode:\n",
    "\tdef __init__(self, val, index):\n",
    "\t\tself.val = val\n",
    "\t\tself.index = index\n",
    "\tdef __lt__(self, o):\n",
    "\t\treturn self.val < o.val\n",
    "\tdef __eq__(self, o):\n",
    "\t\treturn self.val == o.val\n",
    "\n",
    "class Solution:\n",
    "\tdef mergeKLists(self, lists):\n",
    "\t\tl = SkipList()\n",
    "\t\tfor i in range(len(lists)):\n",
    "\t\t\tif None != lists[i]:\n",
    "\t\t\t\tnode = HeadNode(lists[i].val, i)\n",
    "\t\t\t\tl.insert(node)\n",
    "\t\thead = None\n",
    "\t\ttail = None\n",
    "\t\twhile l.size() > 0:\n",
    "\t\t\tnode = l.begin()\n",
    "\t\t\tcurnode = lists[node.pv.index]\n",
    "\t\t\tlists[node.pv.index] = lists[node.pv.index].next\n",
    "\t\t\tif lists[node.pv.index]:\n",
    "\t\t\t\tnewnode = HeadNode(lists[node.pv.index].val, node.pv.index)\n",
    "\t\t\t\tl.insert(newnode)\n",
    "\t\t\tl.erase_node(node)\n",
    "\t\t\tcurnode.next = None\n",
    "\t\t\tif None != tail:\n",
    "\t\t\t\ttail.next = curnode\n",
    "\t\t\telse:\n",
    "\t\t\t\thead = curnode\n",
    "\t\t\ttail = curnode\n",
    "\t\treturn head"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        import copy\n",
    "        if not lists:\n",
    "            return None\n",
    "        result = None\n",
    "        tail_node = None\n",
    "        while True:\n",
    "            lists =[node for node in filter(lambda x: x, lists)]\n",
    "            if not lists:\n",
    "                break\n",
    "            min_node_index = 0\n",
    "            for index in range(1, len(lists)):\n",
    "                if lists[min_node_index].val > lists[index].val:\n",
    "                    min_node_index = index\n",
    "            if result is None:\n",
    "                result = copy.deepcopy(lists[min_node_index])\n",
    "                tail_node = result\n",
    "            else:\n",
    "                tail_node.next = copy.deepcopy(lists[min_node_index])\n",
    "                tail_node = tail_node.next\n",
    "            tail_node.next = None\n",
    "            min_node = lists[min_node_index]\n",
    "            lists[min_node_index] = None if min_node.next is None else min_node.next\n",
    "        return result\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        def merge2Lists(a: ListNode, b: ListNode):\n",
    "            if a == None:\n",
    "                return b\n",
    "            if b == None:\n",
    "                return a\n",
    "            \n",
    "            a, b = (a, b) if a.val < b.val else (b, a)\n",
    "            a.next = merge2Lists(a.next, b)\n",
    "            return a\n",
    "\n",
    "        def dividMerge(lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "            if len(lists) < 1:\n",
    "                return None\n",
    "            elif len(lists) == 1:\n",
    "                return lists[0]\n",
    "\n",
    "            mid = len(lists) // 2\n",
    "            return merge2Lists(dividMerge(lists[:mid]), dividMerge(lists[mid:]))\n",
    "\n",
    "        def countNode(head: ListNode) -> int:\n",
    "            count = 0\n",
    "            while head != None:\n",
    "                head = head.next\n",
    "                count = count + 1\n",
    "            return count\n",
    "        \n",
    "        arr = [x for x in lists if x != None]\n",
    "        arr.sort(key=lambda x: x.val)\n",
    "\n",
    "        return dividMerge(arr)\n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        def merge2Lists(a: ListNode, b: ListNode):\n",
    "            if a == None:\n",
    "                return b\n",
    "            if b == None:\n",
    "                return a\n",
    "            \n",
    "            a, b = (a, b) if a.val < b.val else (b, a)\n",
    "            a.next = merge2Lists(a.next, b)\n",
    "            return a\n",
    "\n",
    "        def dividMerge(lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "            if len(lists) < 1:\n",
    "                return None\n",
    "            elif len(lists) == 1:\n",
    "                return lists[0]\n",
    "\n",
    "            mid = len(lists) // 2\n",
    "            return merge2Lists(dividMerge(lists[:mid]), dividMerge(lists[mid:]))\n",
    "\n",
    "        \n",
    "        arr = [x for x in lists if x != None]\n",
    "        arr.sort(key=lambda x: x.val)\n",
    "\n",
    "        return dividMerge(arr)\n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def merge2lists(self, node1, node2):\n",
    "        if node1 == None:\n",
    "            return node2\n",
    "        if node2 == None:\n",
    "            return node1\n",
    "        res = tmp = ListNode(0)\n",
    "        while node1 and node2:\n",
    "            if node1.val < node2.val:\n",
    "                tmp.next = node1\n",
    "                node1 = node1.next\n",
    "            else:\n",
    "                tmp.next = node2\n",
    "                node2 = node2.next\n",
    "            tmp = tmp.next\n",
    "        if node1:\n",
    "            tmp.next = node1\n",
    "        if node2:\n",
    "            tmp.next = node2\n",
    "        return res.next\n",
    "    def fenzhimerge(self, lists, left, right):\n",
    "        if left > right:\n",
    "            return None\n",
    "        if left == right:\n",
    "            return lists[left]\n",
    "        return self.merge2lists(self.merge2lists(lists[left],lists[right]), self.fenzhimerge(lists,left+1,right-1))\n",
    "        \n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        left = 0\n",
    "        right = len(lists) - 1\n",
    "        return self.fenzhimerge(lists,left,right)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "def quicksort(list):\n",
    "    if len(list)<2:\n",
    "        return list\n",
    "    pivot = list[0]\n",
    "    newlist = list[1:]\n",
    "    greater = [i for i in newlist if i.val <= pivot.val]\n",
    "    upper = [i for i in newlist if i.val > pivot.val]\n",
    "    return quicksort(greater)+[pivot]+quicksort(upper)\n",
    "def change_next(list):\n",
    "    for i in range(0,len(list)-1):\n",
    "        list[i].next = list[i+1]\n",
    "    list[-1].next = None\n",
    "    return list[0]\n",
    "class Solution:\n",
    "    \n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        if len(lists)==0:\n",
    "            return \n",
    "    \n",
    "        newL = []\n",
    "        for i in lists:\n",
    "            thisnode = i\n",
    "            \n",
    "            while thisnode != None:\n",
    "            \n",
    "                newL.append(thisnode)\n",
    "                thisnode = thisnode.next\n",
    "     \n",
    "        finallist = quicksort(newL)\n",
    "        if len(finallist)==0:\n",
    "            return\n",
    "        finallist = change_next(finallist)\n",
    "        return finallist"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        heads = copy.deepcopy(lists)\n",
    "        def end_ls(x):\n",
    "            for i in x:\n",
    "                if i is not None:\n",
    "                    return True\n",
    "            return False\n",
    "        dum = None\n",
    "        p = None\n",
    "        while end_ls(heads):\n",
    "            m = 1e9\n",
    "            h = None\n",
    "            for i in range(len(heads)):\n",
    "                if heads[i] is not None and heads[i].val < m:\n",
    "                    h = i\n",
    "                    m = heads[i].val\n",
    "            heads[h] = heads[h].next\n",
    "            # p.val = m\n",
    "            if p is None:\n",
    "                p = ListNode()\n",
    "                dum = p\n",
    "            else:\n",
    "                p.next = ListNode()\n",
    "                p = p.next\n",
    "            p.val = m\n",
    "            # p = p.next\n",
    "        \n",
    "\n",
    "        return dum\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "\n",
    "# ListNode.__lt__ = lambda a,b: a.val<b.val\n",
    "ListNode.__lt__ = lambda a,b:a.val <b.val\n",
    "from heapq import heappush,heappop,heapify\n",
    "from collections import deque\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        listnums = []\n",
    "        for alist in lists:\n",
    "            arr = deque()\n",
    "            while alist:\n",
    "                arr.append(alist.val)\n",
    "                alist=alist.next\n",
    "            listnums.append(arr)\n",
    "        heapify(listnums)\n",
    "\n",
    "        res = []\n",
    "        while len(listnums)>0:\n",
    "            arr = heappop(listnums)\n",
    "            if len(arr)>0:\n",
    "                res.append(arr.popleft())\n",
    "                heappush(listnums,arr)\n",
    "\n",
    "        # pre = ListNode()\n",
    "        nodes = [ListNode(val) for val in res]\n",
    "        # print(nodes)\n",
    "        for i in range(len(nodes)-1):\n",
    "            nodes[i].next = nodes[i+1]\n",
    "        # print(len(nodes))\n",
    "        return nodes[0] if len(nodes)>0 else None\n",
    "\n",
    "        \n",
    "\n",
    "        \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "        # # res=None\n",
    "        # h = [head for head in lists if head]\n",
    "        # # print(h)\n",
    "        # heapify(h)\n",
    "        # # print(h)\n",
    "        # res=cur = ListNode()\n",
    "        # while h:\n",
    "        #     node = heappop(h)\n",
    "        #     if node.next:\n",
    "        #         heappush(h,node.next)\n",
    "        #     cur.next = node\n",
    "        #     cur = cur.next\n",
    "\n",
    "        # return res.next\n",
    "\n",
    "            \n",
    "\n",
    "\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def iter_linked_list(self, node: Optional[ListNode]):\n",
    "        while node is not None:\n",
    "            yield node.val\n",
    "            node = node.next\n",
    "    \n",
    "    def linked_list_from_iterable(self, iterable):\n",
    "        it = iter(iterable)\n",
    "        try:\n",
    "            head = ListNode(next(it))\n",
    "        except StopIteration:\n",
    "            return None\n",
    "        \n",
    "        tail = head\n",
    "        for item in it:\n",
    "            tail.next = ListNode(item)\n",
    "            tail = tail.next\n",
    "        \n",
    "        return head\n",
    "\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        return self.linked_list_from_iterable(\n",
    "            heapq.merge(*map(self.iter_linked_list, lists))\n",
    "        )\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "def toNode(a) -> ListNode:\n",
    "    head, tail = None, None\n",
    "    for val in a:\n",
    "        if not head:\n",
    "            head = tail = ListNode(val)\n",
    "        else:\n",
    "            tail.next = ListNode(val)\n",
    "            tail = tail.next\n",
    "    return head\n",
    "\n",
    "def toList(head: ListNode | None):\n",
    "    cur = head\n",
    "    while cur:\n",
    "        yield cur.val\n",
    "        cur = cur.next\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        if not lists or all(not li for li in lists):\n",
    "            return None\n",
    "        iterList = [toList(nd) for nd in lists]\n",
    "        li = heapq.merge(*iterList)\n",
    "        return toNode(li)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def merge_2_linked_lists(self, l1, l2):\n",
    "        if l1 is None:\n",
    "            return l2\n",
    "        if l2 is None:\n",
    "            return l1\n",
    "        if l1.val > l2.val:\n",
    "            l2.next = self.merge_2_linked_lists(l1, l2.next)\n",
    "            return l2\n",
    "        else:\n",
    "            l1.next = self.merge_2_linked_lists(l2, l1.next)\n",
    "            return l1\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        ans = None\n",
    "        for linked in lists:\n",
    "            ans = self.merge_2_linked_lists(ans, linked)\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        if lists is None:\n",
    "            return None\n",
    "        n = len(lists)\n",
    "        new_lists = []\n",
    "        for i in range(n):\n",
    "            if lists[i] is not None:\n",
    "                new_lists.append(lists[i])\n",
    "            else:\n",
    "                continue\n",
    "        lists = copy.deepcopy(new_lists)\n",
    "        fake_head = ListNode(val=0, next=None)\n",
    "        p = fake_head\n",
    "        num_list = []\n",
    "        n = len(lists)\n",
    "        flags = n\n",
    "        for i in range(n):\n",
    "            num_list.append(lists[i].val)\n",
    "        while flags > 0:\n",
    "            target_index = self.get_min_index(num_list)\n",
    "            p.next = lists[target_index]\n",
    "            p = p.next\n",
    "            lists[target_index] = lists[target_index].next\n",
    "            if lists[target_index] is None:\n",
    "                num_list[target_index] = 999999\n",
    "                flags -= 1\n",
    "            else:\n",
    "                num_list[target_index] = lists[target_index].val\n",
    "        return fake_head.next\n",
    "\n",
    "    def get_min_index(self, nums):\n",
    "        min_value = min(nums)\n",
    "        min_index = nums.index(min_value)\n",
    "        return min_index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "# 暴力：时间复杂度O(NK)\n",
    "# 优化：时间复杂度O(NlogK) 维护一个小根堆（优先队列）\n",
    "# class Solution:\n",
    "#     def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "#         # print(len(lists))\n",
    "#         import heapq\n",
    "#         dummy = ListNode(0)\n",
    "#         res = dummy\n",
    "#         k = len(lists)\n",
    "#         head = []\n",
    "#         for i in range(k):\n",
    "#             if lists[i]:\n",
    "#                 heapq.heappush(head,(lists[i].val,i))\n",
    "#                 lists[i] = lists[i].next\n",
    "#         # print(head)\n",
    "#         while head:\n",
    "#             val, i = heapq.heappop(head)\n",
    "#             # print(head)\n",
    "#             res.next = ListNode(val)\n",
    "#             res = res.next\n",
    "#             if lists[i]:\n",
    "#                 heapq.heappush(head,(lists[i].val,i))\n",
    "#                 lists[i] = lists[i].next\n",
    "#         return dummy.next\n",
    "\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        if len(lists)==0:\n",
    "            return None\n",
    "        l = 0\n",
    "        r = len(lists)-1\n",
    "        return self.merge_sort(l,r,lists)\n",
    "\n",
    "    def merge_sort(self, l,r,lists):\n",
    "\n",
    "        if l==r:\n",
    "            return lists[l]\n",
    "        \n",
    "        mid = (l+r)//2\n",
    "        l1 = self.merge_sort(l,mid,lists)\n",
    "        l2 = self.merge_sort(mid+1,r,lists)\n",
    "\n",
    "        return self.merge_two(l1,l2)\n",
    "\n",
    "    def merge_two(self,l1,l2):\n",
    "        if not l1: return l2\n",
    "        if not l2: return l1\n",
    "        if l1.val <= l2.val:\n",
    "            l1.next = self.merge_two(l1.next,l2)\n",
    "            return l1\n",
    "        else:\n",
    "            l2.next = self.merge_two(l1,l2.next)\n",
    "            return l2\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        if len(lists) == 0:\n",
    "            return\n",
    "        if len(lists) == 1:\n",
    "            return lists[0]\n",
    "        def merge(l1, l2):\n",
    "            if l1 is None:\n",
    "                return l2\n",
    "            if l2 is None:\n",
    "                return l1\n",
    "            if l1.val < l2.val:\n",
    "                l1.next = merge(l1.next, l2)\n",
    "                return l1       \n",
    "            else:\n",
    "                l2.next = merge(l2.next, l1)\n",
    "                return l2 \n",
    "        node = merge(lists[0],lists[1])\n",
    "        for i in range(2,len(lists)):\n",
    "            node = merge(node,lists[i])\n",
    "        return node\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        def cap(l1,l2):\n",
    "            if not l1:\n",
    "                return l2\n",
    "            if not l2:\n",
    "                return l1\n",
    "            if l1.val>l2.val:\n",
    "                l2.next = cap(l1,l2.next)\n",
    "                return l2\n",
    "            else:\n",
    "                l1.next = cap(l1.next,l2)\n",
    "                return l1\n",
    "        if len(lists)==0:\n",
    "            return None\n",
    "        res = None\n",
    "        for i in lists:\n",
    "            res = cap(res,i)\n",
    "\n",
    "        return res\n",
    "\n",
    "        \n",
    "\n",
    "                \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def merge2Lists(self,list1:Optional[ListNode],list2:Optional[ListNode]) -> Optional[ListNode]:\n",
    "        if not list1:\n",
    "            return list2\n",
    "        elif not list2:\n",
    "            return list1\n",
    "        elif list1.val < list2.val:\n",
    "            list1.next = self.merge2Lists(list1.next,list2)\n",
    "            return list1\n",
    "        else:\n",
    "            list2.next = self.merge2Lists(list2.next,list1)\n",
    "            return list2\n",
    "    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n",
    "        left  = 0\n",
    "        right = len(lists)\n",
    "        mid = (left + right)// 2\n",
    "        if right == 0:\n",
    "            return None\n",
    "        if right == 1:\n",
    "            return lists[0]\n",
    "        left_list = self.mergeKLists(lists[left:mid])\n",
    "        right_list = self.mergeKLists(lists[mid:right])\n",
    "        return self.merge2Lists(left_list,right_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        pre_num = 0\n",
    "        i = head\n",
    "        j = head.next\n",
    "        while j:\n",
    "            pre_num = 0\n",
    "            while j.val != 0:\n",
    "                pre_num += j.val\n",
    "                j = j.next\n",
    "            i.next = j\n",
    "            i, i.val= j, pre_num\n",
    "            j = j.next\n",
    "        return head.next\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        dummy = ListNode(-1)\n",
    "        dummy.next = head\n",
    "        slow = dummy\n",
    "        fast = dummy.next\n",
    "\n",
    "        pre = 0\n",
    "        while fast:\n",
    "            if fast.val == 0:\n",
    "                if pre:\n",
    "                    slow.next.val = pre\n",
    "                    slow = slow.next\n",
    "                pre = 0\n",
    "            else:\n",
    "                pre += fast.val\n",
    "            fast = fast.next\n",
    "        \n",
    "        if pre:\n",
    "            slow.next.val = pre\n",
    "            slow = slow.next\n",
    "        slow.next = None\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        cur = head\n",
    "        dummy = ListNode(0)\n",
    "        tmp = dummy\n",
    "        while cur:\n",
    "            nex = cur.next\n",
    "            sum1 = 0\n",
    "            while nex and nex.val != 0:\n",
    "                sum1 += nex.val\n",
    "                nex = nex.next\n",
    "            if sum1 != 0:\n",
    "                tmp.next = ListNode(sum1)\n",
    "                tmp = tmp.next\n",
    "            #print(tmp)\n",
    "            cur.next = nex\n",
    "            cur = cur.next\n",
    "        return dummy.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        nodelst = []\n",
    "        vallst=[]\n",
    "        th = head\n",
    "        while(th):\n",
    "            nodelst.append(th)\n",
    "            vallst.append(th.val)\n",
    "            th=th.next\n",
    "        tval  = 0\n",
    "        th = head \n",
    "        for i in range(1,len(nodelst)):\n",
    "            tval+=vallst[i]\n",
    "            if vallst[i]==0:\n",
    "                temp = ListNode(tval)\n",
    "                head.next = temp\n",
    "                head= head.next\n",
    "                #head.next = nodelst[i]\n",
    "                #head=head.next\n",
    "\n",
    "                tval = 0\n",
    "        return th.next\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        dummy = ListNode(next=head)\n",
    "        left = dummy\n",
    "        pre, cur = head, head.next\n",
    "        while cur:\n",
    "            tmp = 0\n",
    "            while cur and cur.val != 0:\n",
    "                tmp += cur.val\n",
    "                pre = cur\n",
    "                cur = cur.next\n",
    "            if not cur:\n",
    "                break\n",
    "            cur.val = tmp\n",
    "            tmp = 0\n",
    "            left.next, left, pre, cur = cur, cur, cur, cur.next\n",
    "        return dummy.next\n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        res = ans = ListNode()\n",
    "        head = head.next\n",
    "        temp = 0\n",
    "        while head:\n",
    "            if head.val != 0:\n",
    "                temp += head.val\n",
    "            else:\n",
    "                ans.next = head\n",
    "                ans = ans.next\n",
    "                ans.val = temp\n",
    "                temp = 0\n",
    "                ans.next = head.next\n",
    "\n",
    "            head = head.next\n",
    "        return res.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        Node = ListNode()\n",
    "        \n",
    "        sum = Node\n",
    "        \n",
    "        bb = 0\n",
    "        while head.next!=None:\n",
    "            if head.next.val!=0:\n",
    "                bb += head.next.val\n",
    "                head = head.next\n",
    "                \n",
    "            else:\n",
    "                Node.next = ListNode(val=bb)\n",
    "\n",
    "                Node = Node.next\n",
    "               \n",
    "                bb = 0                \n",
    "                head.next = head.next.next\n",
    "    \n",
    "        return sum.next\n",
    "        \n",
    "\n",
    "\n",
    "\n",
    "                \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        dummy = cur = ListNode(-1)\n",
    "        v = 0\n",
    "        head = head.next\n",
    "        while head:\n",
    "            v += head.val\n",
    "            if head.val == 0:\n",
    "                head.val = v\n",
    "                cur.next = head \n",
    "                cur = cur.next\n",
    "                v = 0\n",
    "            head = head.next\n",
    "        return dummy.next\n",
    "            \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        dummy = ListNode()\n",
    "        pointer = dummy\n",
    "        while head is not None:\n",
    "            if head.val == 0:\n",
    "                head = head.next\n",
    "                while head is not None and head.next.val != 0:\n",
    "                    head.next.val += head.val\n",
    "                    head = head.next\n",
    "                pointer.next = head\n",
    "                pointer = pointer.next\n",
    "            if head is not None:    \n",
    "                head = head.next\n",
    "\n",
    "\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        arr=[]\n",
    "        i=head\n",
    "        while i.next:\n",
    "            if i.next.val!=0:\n",
    "                i.next.val+=i.val\n",
    "            else:\n",
    "                arr.append(i.val)\n",
    "            i=i.next\n",
    "        head=ListNode(arr[0])\n",
    "        temp=head\n",
    "        for i in range(1,len(arr)):\n",
    "            node=ListNode(arr[i])\n",
    "            temp.next=node\n",
    "            temp=node\n",
    "        return head\n",
    "\n",
    "\n",
    "            \n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        cur = head\n",
    "        dcur = head.next\n",
    "        sum_val = 0\n",
    "        while dcur != None:\n",
    "            if dcur.val != 0:\n",
    "                sum_val += dcur.val\n",
    "            if dcur.val == 0:\n",
    "                cur.next = ListNode(sum_val,dcur)\n",
    "                cur = dcur\n",
    "                sum_val = 0\n",
    "            dcur = dcur.next\n",
    "\n",
    "        flag  = 0\n",
    "        cur = head\n",
    "        while cur != None:\n",
    "            if cur.val != 0 and flag == 1:\n",
    "                new_head.next = ListNode(cur.val)    \n",
    "                new_head = new_head.next\n",
    "            if cur.val != 0 and flag == 0:\n",
    "                new_head = ListNode(cur.val)\n",
    "                return_head = new_head\n",
    "                flag = 1\n",
    "                \n",
    "\n",
    "            cur = cur.next\n",
    "        \n",
    "        return return_head"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        virtualhead=ListNode(next=head)\n",
    "        pre=virtualhead\n",
    "        cur=head\n",
    "        while cur:\n",
    "            count=0\n",
    "            while  cur and cur.val!=0:\n",
    "                count+=cur.val\n",
    "                cur=cur.next\n",
    "            if cur and cur.val==0:\n",
    "                node=ListNode(val=count)\n",
    "                pre.next=node\n",
    "                pre=node\n",
    "                cur=cur.next\n",
    "        return virtualhead.next.next\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        start = head.next\n",
    "        nodelist = []; value = 0\n",
    "        while(start != None):\n",
    "            if start.val == 0:\n",
    "                nodelist.append(value)\n",
    "                value = 0\n",
    "            else:\n",
    "                value += start.val\n",
    "            start = start.next\n",
    "        answer = ListNode(nodelist[0], None)\n",
    "        pointer = answer\n",
    "        for count in nodelist[1:]:\n",
    "            pointer.next = ListNode(count, None)\n",
    "            pointer = pointer.next\n",
    "        return answer\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        dummy = tail = ListNode()\n",
    "        total = 0\n",
    "        cur = head.next\n",
    "\n",
    "        while cur:\n",
    "            if cur.val == 0:\n",
    "                node = ListNode(total)\n",
    "                tail.next = node\n",
    "                tail = tail.next\n",
    "                total = 0\n",
    "            else:\n",
    "                total += cur.val\n",
    "            \n",
    "            cur = cur.next\n",
    "        \n",
    "        return dummy.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        ans = ListNode()\n",
    "        tmp = ans\n",
    "        cur = 0\n",
    "        while head:\n",
    "            if head.val == 0 and cur:\n",
    "                tmp.next = ListNode(cur)\n",
    "                tmp = tmp.next\n",
    "                cur = 0\n",
    "            cur += head.val\n",
    "            head = head.next\n",
    "        return ans.next\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        ans = ListNode(0)\n",
    "        q = ans\n",
    "        stack = []\n",
    "        cur = head\n",
    "        while head:\n",
    "            if head.val==0 and stack:\n",
    "                tmp = 0\n",
    "                while stack:\n",
    "                    tmp += stack.pop() \n",
    "                q.next = ListNode(tmp)\n",
    "                q = q.next\n",
    "            elif head!=0:\n",
    "                stack.append(head.val)\n",
    "            head = head.next\n",
    "        return ans.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        data=[]\n",
    "        while head:\n",
    "            data.append(head.val)\n",
    "            head=head.next\n",
    "        left=0;tmp=[]\n",
    "        for i in range(1,len(data)):\n",
    "            if data[i]==0:\n",
    "                tmp.append(data[left:i])\n",
    "                left=i+1\n",
    "        tmp=[sum(x) for x in tmp]\n",
    "        ans1=ans2=ListNode(0)\n",
    "        for val in tmp:\n",
    "            ans2.next=ListNode(val)\n",
    "            ans2=ans2.next\n",
    "        return ans1.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        count=0\n",
    "        list1=[]\n",
    "        while head and head.next:\n",
    "            while head.next.val!=0:\n",
    "                count+=head.next.val\n",
    "                head=head.next\n",
    "            list1.append(count)\n",
    "            head=head.next\n",
    "            count=0\n",
    "        list1=list1[::-1]\n",
    "    \n",
    "        head=ListNode(list1.pop())\n",
    "        node=head\n",
    "        while list1:\n",
    "            node.next=ListNode(list1.pop())\n",
    "            node=node.next\n",
    "            \n",
    "        return head\n",
    "        \n",
    "        \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        nums = []\n",
    "        while head:\n",
    "            nums.append(head.val)\n",
    "            head = head.next\n",
    "        stk = []\n",
    "        while nums:\n",
    "            cur = nums.pop()\n",
    "            if cur == 0:\n",
    "                sum1 = 0\n",
    "                while nums and nums[-1] != 0:\n",
    "                    sum1 += nums.pop()\n",
    "                if sum1:\n",
    "                    stk.append(sum1)\n",
    "        res = ListNode(0)\n",
    "        pre = res\n",
    "        while stk:\n",
    "            pre.next = ListNode(stk.pop())\n",
    "            pre = pre.next\n",
    "        return res.next\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        arr = []\n",
    "        d_head = ListNode(-1)\n",
    "        d_head.next = head\n",
    "        d_head = d_head.next\n",
    "        while d_head:\n",
    "            arr.append(d_head.val)\n",
    "            d_head = d_head.next\n",
    "\n",
    "        arr = list(reversed(arr))\n",
    "        print(arr)\n",
    "        r_head = ListNode(-1)\n",
    "        d_head = r_head\n",
    "        while len(arr):\n",
    "            cnt,zero_cnt = 0,0\n",
    "\n",
    "            while len(arr) and zero_cnt <= 1:\n",
    "                top_v = arr.pop()\n",
    "                cnt += top_v\n",
    "                if top_v == 0:\n",
    "                    zero_cnt += 1\n",
    "\n",
    "            d_head.next = ListNode(cnt) if cnt > 0 else None\n",
    "            if zero_cnt == 2: arr.append(0)\n",
    "\n",
    "            d_head = d_head.next\n",
    "        return r_head.next\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        res = []\n",
    "        ans = []\n",
    "        while head:   \n",
    "            res.append(head.val)\n",
    "            head = head.next\n",
    "        i = 0\n",
    "        \n",
    "        while i < len(res):\n",
    "            tmp = 0\n",
    "            if res[i] == 0:\n",
    "                j = i + 1\n",
    "                while j < len(res) and res[j] != 0:\n",
    "                    tmp += res[j]\n",
    "                    j += 1\n",
    "                if tmp != 0:\n",
    "                    ans.append(tmp)\n",
    "                i = j\n",
    "            else:\n",
    "                i += 1\n",
    "        head = ListNode()\n",
    "        cur = head\n",
    "        for i in ans:\n",
    "            cur.next = ListNode(i)\n",
    "            cur = cur.next\n",
    "        return head.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        ret = []\n",
    "        while head:\n",
    "            ret.append(head.val)\n",
    "            head = head.next\n",
    "        cnt, left, right = 0, 0, 1\n",
    "        while right < len(ret):\n",
    "            while right < len(ret) and ret[right] != 0:\n",
    "                right += 1\n",
    "            ret[cnt] = sum(ret[left:right])\n",
    "            cnt += 1\n",
    "            left = right\n",
    "            right += 1\n",
    "        print(ret)\n",
    "        pre = ListNode(0)\n",
    "        while cnt:\n",
    "            temp = ListNode(ret[cnt-1])\n",
    "            temp.next = pre.next\n",
    "            pre.next = temp\n",
    "            cnt -= 1\n",
    "        return pre.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        left, right = head, head\n",
    "        result_head = None\n",
    "        result_tail = None\n",
    "\n",
    "        while left and right and left.next is not None and right.next is not None:\n",
    "            if left.val == 0 and right.val == 0:\n",
    "                left = left.next\n",
    "                right = right.next\n",
    "\n",
    "                if result_head is None:\n",
    "                    result_tail = result_head = ListNode()\n",
    "                else:\n",
    "                    result_tail.next = ListNode()\n",
    "                    result_tail = result_tail.next\n",
    "            elif left.val != 0 and right.val != 0:\n",
    "                result_tail.val += right.val\n",
    "                right = right.next\n",
    "            elif left.val != 0 and right.val == 0:\n",
    "                left = right\n",
    "\n",
    "        return result_head if result_head.val != 0 else None\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        ans=ListNode(0)\n",
    "        p=ans\n",
    "        x=head.next\n",
    "        c=0\n",
    "        while x:\n",
    "            if x.val==0:\n",
    "                p.next=ListNode(c)\n",
    "                p=p.next\n",
    "                c=0\n",
    "            else:\n",
    "                c+=x.val\n",
    "            x=x.next\n",
    "        return ans.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        cnt = Counter()\n",
    "        for v, w in chain(items1, items2):\n",
    "            cnt[v] += w\n",
    "        return sorted(cnt.items())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        def getFirst(elem):\n",
    "            return elem[0]\n",
    "        items = items1 + items2\n",
    "        items.sort(key = getFirst)\n",
    "        ans = [[items[0][0],items[0][1]]]\n",
    "        for i in range(1,len(items)):\n",
    "            if items[i][0] == ans[len(ans)-1][0]:\n",
    "                ans[len(ans)-1][1] = ans[len(ans)-1][1] + items[i][1]\n",
    "            else:\n",
    "                ans.append(items[i])\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        fpr = Counter()\n",
    "        for v in items1:\n",
    "            fpr[v[0]] += v[1]\n",
    "        for p in items2:\n",
    "            fpr[p[0]] += p[1]\n",
    "        fpr = sorted(fpr.items())\n",
    "        return fpr\n",
    "        \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        hashMap = { value : weight for value, weight in items1 }\n",
    "        for value, weight in items2:\n",
    "            if value in hashMap:\n",
    "                hashMap[value] += weight\n",
    "            else:\n",
    "                hashMap[value] = weight\n",
    "        \n",
    "        return sorted([ (value, hashMap[value]) for value in hashMap.keys() ])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map={}\n",
    "        for a,b in items1:\n",
    "            map[a]=b\n",
    "        for a,b in items2:\n",
    "            if a in map:\n",
    "                map[a] += b\n",
    "            else:\n",
    "                map[a] = b\n",
    "        return sorted([a,b] for a,b in map.items())\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        hash = {v: w for v, w in items1}\n",
    "        for v, w in items2:\n",
    "            hash[v] = hash.get(v, 0) + w\n",
    "        return sorted(list(hash.items()))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        temp={}\n",
    "        for tt in items1:\n",
    "            temp[tt[0]]=tt[1]\n",
    "        for tt in items2:\n",
    "            if temp.get(tt[0]):\n",
    "                temp[tt[0]]+=tt[1]\n",
    "            else:\n",
    "                temp[tt[0]]=tt[1]\n",
    "        res=sorted(temp.items(),key=lambda x:x[0])\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items1 += items2\n",
    "        items1.sort()\n",
    "        r = [[items1[0][0], items1[0][1]]]\n",
    "        for i in range(1, len(items1)):\n",
    "            if items1[i][0] == items1[i-1][0]:\n",
    "                r[-1][1] += items1[i][1]\n",
    "            else:\n",
    "                r.append(items1[i])\n",
    "        return r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map = Counter()\n",
    "        for a, b in items1:\n",
    "            map[a] += b\n",
    "        for a, b in items2:\n",
    "            map[a] += b\n",
    "        return sorted([a, b] for a, b in map.items())\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items3 = items2 + items1\n",
    "        d = {}\n",
    "        for k, v in items3:\n",
    "            if d.get(k):\n",
    "                d[k] += v\n",
    "            else:\n",
    "                d[k] = v\n",
    "        return sorted([a, b] for a, b in d.items())\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        item_weight = collections.defaultdict(int)\n",
    "\n",
    "        for item in items1:\n",
    "            item_weight[item[0]] += item[1]\n",
    "        for item in items2:\n",
    "            item_weight[item[0]] += item[1]\n",
    "        result = [[key, item_weight[key]] for key in item_weight]\n",
    "        return sorted(result, key=lambda x: x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items1.sort()\n",
    "        items2.sort()\n",
    "        ret = []\n",
    "        i = 0\n",
    "        j = 0\n",
    "        while i < len(items1) and j < len(items2):\n",
    "            if items1[i][0] == items2[j][0]:\n",
    "                ret.append([items1[i][0], items1[i][1] + items2[j][1]])\n",
    "                i += 1\n",
    "                j += 1\n",
    "            elif items1[i][0] > items2[j][0]:\n",
    "                ret.append([items2[j][0], items2[j][1]])\n",
    "                j += 1\n",
    "            else:\n",
    "                ret.append([items1[i][0], items1[i][1]])\n",
    "                i += 1\n",
    "        if i < len(items1):\n",
    "            ret += items1[i:]\n",
    "        if j < len(items2):\n",
    "            ret += items2[j:]\n",
    "        return ret\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        # items1=dict(items1)\n",
    "        # items2=dict(items2)\n",
    "        # for (i,j) in items2.items():\n",
    "        #     if i not in items1.keys():\n",
    "        #         items1.setdefault(i,j)\n",
    "        #     else:\n",
    "        #         items1[i]+=j\n",
    "        # return sorted(list(items1.items()))\n",
    "        map=Counter()\n",
    "        for a,b in items1:\n",
    "            map[a]+=b\n",
    "        for a,b in items2:\n",
    "            map[a]+=b\n",
    "        return sorted(list(map.items()))\n",
    "\n",
    "        \n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        hashmap = {}\n",
    "        for item in items1:\n",
    "            hashmap[item[0]] = item[1]\n",
    "        for item in items2:\n",
    "            if item[0] in hashmap:\n",
    "                hashmap[item[0]]+=item[1]\n",
    "            else:\n",
    "                hashmap[item[0]] = item[1]\n",
    "        \n",
    "        res = []\n",
    "        for key in sorted(hashmap.keys()):\n",
    "            res.append([key, hashmap[key]])\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution(object):\n",
    "    def mergeSimilarItems(self, items1, items2):\n",
    "        items1.sort()\n",
    "        items2.sort()\n",
    "        ans=[]\n",
    "        n1,n2=len(items1),len(items2)\n",
    "        i,j=0,0\n",
    "        while i<n1 and j<n2:\n",
    "            if items1[i][0]==items2[j][0]:\n",
    "                item=[items1[i][0],items1[i][1]+items2[j][1]]\n",
    "                ans.append(item)\n",
    "                i+=1\n",
    "                j+=1\n",
    "            elif items1[i][0]>items2[j][0]:\n",
    "                ans.append(items2[j])\n",
    "                j+=1\n",
    "            else:\n",
    "                ans.append(items1[i])\n",
    "                i+=1\n",
    "        if i==n1:\n",
    "            # n2>n1\n",
    "            ans.extend(items2[j:])\n",
    "\n",
    "        elif j==n2:\n",
    "            # n1>n2\n",
    "            ans.extend(items1[i:])\n",
    "        ans.sort()\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        r = defaultdict(int)\n",
    "        for v, w in chain(items1, items2):\n",
    "            r[v] += w\n",
    "        return sorted([k, v] for k, v in r.items())\n",
    "\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        res = []\n",
    "        hash_d = {}\n",
    "        items1.extend(items2)\n",
    "        for l in items1:\n",
    "            hash_d[l[0]] = hash_d.get(l[0],0) + l[1]\n",
    "        return sorted([[k,v] for k,v in hash_d.items()])\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map=Counter()\n",
    "        for a,b in items1:\n",
    "            map[a]+=b\n",
    "        \n",
    "        for a,b in items2:\n",
    "            map[a]+=b\n",
    "        \n",
    "        return sorted([a,b] for a,b in map.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        total = items1 + items2\n",
    "        n = len(total)\n",
    "        total.sort()\n",
    "        weight = total[0][1]\n",
    "        ret =[]\n",
    "        for i in range(1,n):\n",
    "            if total[i][0] == total[i-1][0]:\n",
    "                weight =weight +total[i][1]\n",
    "            else:\n",
    "                ret.append([total[i-1][0],weight])\n",
    "                weight = total[i][1]\n",
    "        ret.append([total[-1][0],weight])\n",
    "        ret.sort()\n",
    "        return ret\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        cnt = Counter()\n",
    "        for v, w in chain(items1, items2):\n",
    "            cnt[v] += w\n",
    "        return sorted(cnt.items())\n",
    "\n",
    "\n",
    "           \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map = Counter()\n",
    "        for a, b in items1:\n",
    "            map[a] += b\n",
    "        for a, b in items2:\n",
    "            map[a] += b\n",
    "        return sorted([a, b] for a, b in map.items())\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        cnt = Counter()\n",
    "        for v, w in chain(items1, items2):\n",
    "            cnt[v] += w\n",
    "        # return [[v, cnt[v]] for v in range(1, 1001) if cnt[v]]\n",
    "        return sorted(cnt.items())\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items1.extend(items2)\n",
    "        items1.sort()\n",
    "        res=[items1[0]]\n",
    "        for i in range(1,len(items1)):\n",
    "            if res[-1][0]==items1[i][0]:\n",
    "                res[-1][1]+=items1[i][1]\n",
    "            else:\n",
    "                res.append(items1[i])\n",
    "        res.sort()\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map = Counter()\n",
    "        for a, b in items1:\n",
    "            map[a] += b\n",
    "        for a, b in items2:\n",
    "            map[a] += b\n",
    "        return sorted([a, b] for a, b in map.items())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map = Counter()\n",
    "        for v, w in items1:\n",
    "            map[v] += w\n",
    "        for v, w in items2:\n",
    "            map[v] += w\n",
    "        return sorted([v, w] for v, w in map.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map=collections.Counter()\n",
    "        for a,b in items1:\n",
    "            map[a]+=b\n",
    "        for a,b in items2:\n",
    "            map[a]+=b\n",
    "        return sorted([a,b] for a,b in map.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map = Counter()\n",
    "        for a, b in items1:\n",
    "            map[a] += b\n",
    "        for a, b in items2:    \n",
    "            map[a] += b\n",
    "        return sorted([a, b] for a, b in map.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        res = []\n",
    "        hash_d = {}\n",
    "        items1.extend(items2)\n",
    "        for l in items1:\n",
    "            hash_d[l[0]] = hash_d.get(l[0],0) + l[1]\n",
    "        return sorted([[k,v] for k,v in hash_d.items()])\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        _dict = {}\n",
    "        for item in items1 + items2:\n",
    "            if item[0] not in _dict:\n",
    "                _dict[item[0]] = item[1]\n",
    "            else:\n",
    "                _dict[item[0]] += item[1]\n",
    "\n",
    "        _list = []\n",
    "        for k,v in _dict.items():\n",
    "            _list.append([k,v])\n",
    "\n",
    "        _list.sort(key=lambda x: x[0])\n",
    "\n",
    "        return _list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        sum_=items1+items2\n",
    "        value=[]\n",
    "        sum_.sort()\n",
    "        for i in sum_:\n",
    "            value.append(i[0])\n",
    "        # print(value)\n",
    "        values=list(set(value))\n",
    "        values.sort()\n",
    "        ans=[]\n",
    "        for j in values:\n",
    "            mid=[]\n",
    "            for z in sum_:\n",
    "                if j==z[0]:\n",
    "                    mid.append(z[1])\n",
    "            # print(mid)\n",
    "            # print(sum(mid))\n",
    "            ans.append([j,sum(mid)])\n",
    "            # print(ans)\n",
    "        return ans \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        dic  = {}\n",
    "        for i in items1:\n",
    "            if i[0] in dic:\n",
    "                dic[i[0]] += i[1]\n",
    "            else:\n",
    "                dic[i[0]] = i[1]\n",
    "        \n",
    "        for i in items2:\n",
    "            if i[0] in dic:\n",
    "                dic[i[0]] += i[1]\n",
    "            else:\n",
    "                dic[i[0]] = i[1]\n",
    "        ans = []\n",
    "        for i in dic:\n",
    "            ans.append([i,dic[i]])\n",
    "        ans.sort()\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        a={}\n",
    "        for i in items1:\n",
    "            if i[0] not in a:\n",
    "                a[i[0]]=i[1]\n",
    "            else:\n",
    "                a[i[0]]+=i[1]\n",
    "        for i in items2:\n",
    "            if i[0] not in a:\n",
    "                a[i[0]]=i[1]\n",
    "            else:\n",
    "            \ta[i[0]]+=i[1]\n",
    "        ret=[]\n",
    "        for i in a:\n",
    "            ret.append([i,a[i]])\n",
    "        ret.sort(key=lambda a:a[0])\n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        a = len(items1)\n",
    "        b = len(items2)\n",
    "        if a < b:\n",
    "            items1, items2 = items2, items1\n",
    "        for i in range(len(items2)):\n",
    "            n = 0\n",
    "            for j in range(len(items1)):\n",
    "                if items1[j][0] == items2[i][0]:\n",
    "                    items1[j][1] = items1[j][1] + items2[i][1]\n",
    "                else:\n",
    "                    n += 1\n",
    "            if n == len(items1):\n",
    "                items1.append(items2[i])\n",
    "        items1.sort(key=lambda x: x[0])\n",
    "        return items1\n",
    "                     "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        mp = {}\n",
    "        for item in items1:\n",
    "            mp[item[0]] = mp.get(item[0], 0) + item[1]\n",
    "\n",
    "        for item in items2:\n",
    "            mp[item[0]] = mp.get(item[0], 0) + item[1]\n",
    "        \n",
    "        ans = []\n",
    "        for item in mp.items():\n",
    "            ans.append(item)\n",
    "        \n",
    "        ans.sort()\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        counter = dict()\n",
    "        for v , w in items1 :\n",
    "            if counter.get(v) is None :\n",
    "                counter[v] = w \n",
    "            else :\n",
    "                counter[v] += w \n",
    "        for v , w in items2 :\n",
    "            if counter.get(v) is None :\n",
    "                counter[v] = w \n",
    "            else :\n",
    "                counter[v] += w \n",
    "        return sorted(list(counter.items()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        dic = {}\n",
    "        for k, v in items2 + items1:\n",
    "            if k in dic:\n",
    "                dic[k] += v\n",
    "            else:\n",
    "                dic[k] = v\n",
    "        return sorted([[k, v] for k, v in dic.items()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        dic = {k: v for k, v in items1}\n",
    "        for k, v in items2:\n",
    "            if k in dic:\n",
    "                dic[k] += v\n",
    "            else:\n",
    "                dic[k] = v\n",
    "        return sorted([[k, v] for k, v in dic.items()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        d = defaultdict(int)\n",
    "        for v, w in items1:\n",
    "            d[v] += w\n",
    "        for v, w in items2:\n",
    "            d[v] += w\n",
    "        ans = [[i, d[i]] for i in sorted(d.keys())]\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1, items2):\n",
    "        merged_items = {}\n",
    "        \n",
    "        for item in items1 + items2:\n",
    "            value, weight = item\n",
    "            if value in merged_items:\n",
    "                merged_items[value] += weight\n",
    "            else:\n",
    "                merged_items[value] = weight\n",
    "        \n",
    "        ret = [[value, weight] for value, weight in merged_items.items()]\n",
    "        ret.sort(key=lambda x: x[0])\n",
    "        \n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        res=Counter()\n",
    "        for i in items1+items2:\n",
    "            res[i[0]]+=i[1]\n",
    "        \n",
    "        return sorted([a,b] for a,b in res.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map = Counter()\n",
    "        for a, b in items1:\n",
    "            map[a] += b\n",
    "        for a, b in items2:\n",
    "            map[a] += b\n",
    "        return sorted([a, b] for a, b in map.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        if len(items1) < len(items2):\n",
    "            items1, items2 = items2, items1\n",
    "        ls1 = dict(items1)\n",
    "        for n in range(len(items2)):\n",
    "            if items2[n][0] in ls1:\n",
    "                ls1[items2[n][0]] = ls1.get(items2[n][0]) + items2[n][1]\n",
    "            else:\n",
    "                ls1[items2[n][0]] = items2[n][1]\n",
    "        del items2\n",
    "        ls = list(ls1.items())\n",
    "        ls.sort(key=lambda x: x[0])\n",
    "        return ls\n",
    "                     "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        dic = {}\n",
    "        for i in items1:\n",
    "            dic[i[0]] = i[1]\n",
    "        for i in items2:\n",
    "            try:\n",
    "                dic[i[0]] += i[1]\n",
    "            except:\n",
    "                dic[i[0]] = i[1]\n",
    "        ans = []\n",
    "        for key in dic:\n",
    "            ans.append([key, dic[key]])\n",
    "        ans.sort()\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        d = {}\n",
    "        for item in items1:\n",
    "            k, v = item\n",
    "            if k in d:\n",
    "                d[k] += v\n",
    "            else:\n",
    "                d[k] = v\n",
    "        for item in items2:\n",
    "            k, v = item\n",
    "            if k in d:\n",
    "                d[k] += v\n",
    "            else:\n",
    "                d[k] = v\n",
    "        ans = [[k, v] for k, v in d.items()]\n",
    "        ans.sort(key=lambda x: x[0])\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items = items1 + items2\n",
    "        d = {}\n",
    "        for x, y in items:\n",
    "            d[x] = d.get(x, 0) + y\n",
    "        return sorted(d.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map = Counter()\n",
    "        for a, b in items1:\n",
    "            map[a] += b\n",
    "        for a, b in items2:\n",
    "            map[a] += b\n",
    "        return sorted([a, b] for a, b in map.items())\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        d = collections.defaultdict(int)\n",
    "        for x, y in items1:\n",
    "            d[x] += y\n",
    "        for x, y in items2:\n",
    "            d[x] += y\n",
    "\n",
    "        res = list(d.items())\n",
    "        # print(d)\n",
    "        res.sort()\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        if len(items1) < len(items2):\n",
    "            items1, items2 = items2, items1\n",
    "        ls1 = dict(items1)\n",
    "        del items1\n",
    "        for n in range(len(items2)):\n",
    "            if items2[n][0] in ls1:\n",
    "                ls1[items2[n][0]] = ls1.get(items2[n][0]) + items2[n][1]\n",
    "            else:\n",
    "                ls1[items2[n][0]] = items2[n][1]\n",
    "        del items2\n",
    "        ls = list(ls1.items())\n",
    "        ls.sort(key=lambda x: x[0])\n",
    "        return ls\n",
    "                     "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        hax = dict(items1)\n",
    "        for i in items2:\n",
    "            if i[0] not in hax:\n",
    "                hax[i[0]] = i[1]\n",
    "            else:\n",
    "                hax[i[0]] += i[1]\n",
    "        ret = []\n",
    "        for i in sorted(hax):\n",
    "            ret.append([i, hax[i]])\n",
    "        return ret\n",
    "        \n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        dict1={}\n",
    "        dict2={}\n",
    "\n",
    "        for a in items1:\n",
    "            dict1[a[0]]=a[1]\n",
    "        \n",
    "        for b in items2:\n",
    "            dict2[b[0]]=b[1]\n",
    "        \n",
    "        for temp in dict1.keys():\n",
    "            if temp in dict2.keys():\n",
    "                dict2[temp]+=dict1[temp]\n",
    "            else:\n",
    "                dict2[temp] = dict1[temp]\n",
    "        l_sort=[]\n",
    "        for i in dict2.keys():\n",
    "            l_sort.append(i)\n",
    "        l_sort.sort()\n",
    "        result=[]\n",
    "        for j in l_sort:\n",
    "            result.append([j,dict2[j]])\n",
    "\n",
    "        print(result)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items1=Counter({i[0]:i[1] for i in items1})\n",
    "        items2=Counter({i[0]:i[1] for i in items2})\n",
    "        res=[[key,value] for key,value in dict(items1+items2).items()]\n",
    "        res.sort(key=lambda x:x[0])\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        res = []\n",
    "        hash_d = {}\n",
    "        items1.extend(items2)\n",
    "        for l in items1:\n",
    "            hash_d[l[0]] = hash_d.get(l[0],0) + l[1]\n",
    "        return sorted([[k,v] for k,v in hash_d.items()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import Counter\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        ds1,ds2 = Counter(),Counter()\n",
    "        for x in items1:\n",
    "            ds1[x[0]] = x[1]\n",
    "        for x in items2:\n",
    "            ds2[x[0]] = x[1]\n",
    "        return sorted([[k,v] for k,v in (ds1 + ds2).items()],key = lambda x:x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        res = []\n",
    "        hash_d = {}\n",
    "        items1.extend(items2)\n",
    "        for l in items1:\n",
    "            hash_d[l[0]] = hash_d.get(l[0],0) + l[1]\n",
    "        return sorted([[k,v] for k,v in hash_d.items()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        cnt=collections.defaultdict(int)\n",
    "        for val,wei in items1:\n",
    "            cnt[val]+=wei\n",
    "        for val,wei in items2:\n",
    "            cnt[val]+=wei\n",
    "        res=[]\n",
    "        # print(cnt)\n",
    "        for val,wei in cnt.items():\n",
    "            # print(val)\n",
    "            res.append([val,wei])\n",
    "        # print(res)\n",
    "        res.sort(key=lambda x:x[0])\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        cnt = Counter(dict(items1))\n",
    "        cnt += dict(items2)\n",
    "        return sorted(cnt.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map = Counter()\n",
    "        for a, b in items1:\n",
    "            map[a] += b\n",
    "        for a, b in items2:\n",
    "            map[a] += b\n",
    "        return sorted([a, b] for a, b in map.items())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map = Counter()\n",
    "        for a, b in items1:\n",
    "            map[a] += b\n",
    "        for a, b in items2:\n",
    "            map[a] += b\n",
    "        return sorted([a, b] for a, b in map.items())\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items1.sort(key = lambda x:x[0])\n",
    "        items2.sort(key = lambda x:x[0])\n",
    "\n",
    "        ret = Counter()\n",
    "        for a,b in items1:\n",
    "            ret[a] += b\n",
    "        for a,b in items2:\n",
    "            ret[a] += b\n",
    "\n",
    "        return sorted([v,w] for v,w in ret.items())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import Counter\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        ds1,ds2 = Counter(),Counter()\n",
    "        for x in items1:\n",
    "            ds1[x[0]] = x[1]\n",
    "        for x in items2:\n",
    "            ds2[x[0]] = x[1]\n",
    "        return sorted([[k,v] for k,v in (ds1 + ds2).items()],key = lambda x:x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        map = collections.Counter()\n",
    "        for a,b in items1:\n",
    "            map[a] += b\n",
    "        for a,b in items2:\n",
    "            map[a] += b\n",
    "        return sorted([a,b] for a,b in map.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        item = []\n",
    "        for i in range(len(items1)):\n",
    "            item.append(items1[i][0])\n",
    "        for i in range(len(items2)):\n",
    "            item.append(items2[i][0])\n",
    "        item = list(set(item))\n",
    "        weight = [0] * len(item)\n",
    "        for i in range(len(items1)):\n",
    "            weight[item.index(items1[i][0])] += items1[i][1]\n",
    "        for i in range(len(items2)):\n",
    "            weight[item.index(items2[i][0])] += items2[i][1]\n",
    "        res = []\n",
    "        for i in range(len(item)):\n",
    "            res.append([item[i], weight[i]])\n",
    "        res = sorted(res, key = lambda x:x[0], reverse = False)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        r = defaultdict(int)\n",
    "        for value, weight in chain(items1, items2):\n",
    "            r[value] += weight\n",
    "        return sorted([k, v] for k, v in r.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        m,n,res=len(items1),len(items2),[]\n",
    "        mp=dict()\n",
    "        for i in range(m):\n",
    "            mp[items1[i][0]]=items1[i][1]\n",
    "        for i in range(n):\n",
    "            if mp.get(items2[i][0],0)!=0:\n",
    "                mp[items2[i][0]]+=items2[i][1]\n",
    "            else:\n",
    "                mp[items2[i][0]]=items2[i][1]\n",
    "        for key,value in mp.items():\n",
    "            res.append([key,value])\n",
    "        res.sort(key=lambda x:x[0])\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        res={}\n",
    "        for i in items1+items2:\n",
    "            if i[0] in res:\n",
    "                res[i[0]]+=i[1]\n",
    "            else:\n",
    "                res[i[0]]=i[1]\n",
    "        res=sorted(res.items(),key=lambda x:x[0])\n",
    "        print(res)\n",
    "        return [list(i) for i in res]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items3 = items2 + items1\n",
    "        res = []\n",
    "\n",
    "        counter = dict(Counter(map(lambda x: x[0], items3)))\n",
    "\n",
    "        for key in counter.keys():\n",
    "            s = sum(map(lambda x: x[1], filter(lambda x: x[0] == key, items3)))\n",
    "            res.append([key, s])\n",
    "            \n",
    "        res.sort(key=lambda x: x[0])\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        a = dict(items1)\n",
    "        for i in items2:\n",
    "            if i[0] in a:\n",
    "                a[i[0]] += i[1]\n",
    "            else:\n",
    "                a[i[0]] = i[1]\n",
    "        b = [[i, a[i] ] for i in a]\n",
    "        return sorted(b, key=lambda x: x[0])\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items1=dict(items1)\n",
    "        items2=dict(items2)\n",
    "        for (i,j) in items2.items():\n",
    "            if i not in items1.keys():\n",
    "                items1.setdefault(i,j)\n",
    "            else:\n",
    "                items1[i]+=j\n",
    "        return sorted(list(items1.items()))\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        m = {}\n",
    "        for v,w in items1:\n",
    "            m[v] = w\n",
    "        for v,w in items2:\n",
    "            if v in m:\n",
    "                m[v] += w\n",
    "            else:\n",
    "                m[v] = w\n",
    "        ans = []\n",
    "        for v,w in m.items():\n",
    "            ans.append([v,w])\n",
    "        return sorted(ans,key = lambda x: x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items = items1 + items2\n",
    "        values = list(set([x[0] for x in items]))\n",
    "        values.sort()\n",
    "        ret = [[val, 0] for val in values]\n",
    "        for item in items:\n",
    "            for idx, x in enumerate(ret):\n",
    "                if item[0] == x[0]:\n",
    "                    ret[idx][1] += item[1]\n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        if len(items1) < len(items2):\n",
    "            items1, items2 = items2, items1\n",
    "        ls1 = dict(items1)\n",
    "        del items1\n",
    "        for n in range(len(items2)):\n",
    "            if items2[n][0] in ls1:\n",
    "                ls1[items2[n][0]] = ls1.get(items2[n][0]) + items2[n][1]\n",
    "            else:\n",
    "                ls1[items2[n][0]] = items2[n][1]\n",
    "        del items2\n",
    "        ls = list(ls1.items())\n",
    "        ls.sort(key=lambda x: x[0])\n",
    "        return ls\n",
    "                     "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        items1.sort(key=lambda x: x[0])\n",
    "        items2.sort(key=lambda x: x[0])\n",
    "        ret = []\n",
    "        left = 0\n",
    "        right = 0\n",
    "        while left < len(items1) or right < len(items2):\n",
    "            if left < len(items1):\n",
    "                num1 = items1[left]\n",
    "            else:\n",
    "                num1 = [inf, inf]\n",
    "            if right < len(items2):           \n",
    "                num2 = items2[right]\n",
    "            else:\n",
    "                num2 = [inf, inf]\n",
    "            if num1[0] == num2[0]:\n",
    "                ret.append([num1[0], num1[1]+num2[1]])\n",
    "                left += 1\n",
    "                right += 1\n",
    "            elif num1[0] < num2[0]:\n",
    "                ret.append([num1[0], num1[1]])\n",
    "                left += 1\n",
    "            else:\n",
    "                ret.append([num2[0], num2[1]])\n",
    "                right += 1\n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        d = {}\n",
    "        for items in items1:\n",
    "            k = items[0]\n",
    "            v = items[1]\n",
    "            if k in d:\n",
    "                d[k] += v\n",
    "            else:\n",
    "                d[k] = v\n",
    "        \n",
    "        for items in items2:\n",
    "            k = items[0]\n",
    "            v = items[1]\n",
    "            if k in d:\n",
    "                d[k] += v\n",
    "            else:\n",
    "                d[k] = v\n",
    "        \n",
    "        d1 = dict(sorted(d.items(), key=lambda x: x[0]))\n",
    "\n",
    "        final_items = []\n",
    "        for k,v in d1.items():\n",
    "            final_items.append([k, v])\n",
    "        \n",
    "\n",
    "\n",
    "        return final_items\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        # ans = dict()\n",
    "        # for value, weight in items1:\n",
    "        #     ans[value] = weight\n",
    "        ans = {value: weight for value, weight in items1}\n",
    "        for value, weight in items2:\n",
    "            if value not in ans:\n",
    "                ans[value] = weight\n",
    "            else:\n",
    "                ans[value] += weight\n",
    "        ret = []\n",
    "        for value,weight in ans.items():\n",
    "            ret.append([value, weight])\n",
    "        ret.sort(key=lambda x:x[0])\n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# 哈希表，一行写法，将items作为键值对传入dict，然后通过Counter把值加起来\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "\n",
    "        return sorted((Counter(dict(items1)) + Counter(dict(items2))).items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n",
    "        cnt = defaultdict(int)\n",
    "        for x, y in items1:\n",
    "            cnt[x] += y\n",
    "        for x, y in items2:\n",
    "            cnt[x] += y\n",
    "        res = []\n",
    "        tmp = sorted(cnt.items(), key=lambda x:x[0])\n",
    "        for t in tmp:\n",
    "            res.append(list(t))\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        m -= 1\n",
    "        n -= 1\n",
    "        while m >= 0 or n >= 0:   #  or, not and,  one array may be all used!\n",
    "          if n < 0:  # if nums2 is already merged, we can stop now!\n",
    "            break\n",
    "          if m>=0 and nums1[m] >= nums2[n]:\n",
    "            nums1[m+n+1] = nums1[m]\n",
    "            m -= 1\n",
    "          else:\n",
    "            nums1[m+n+1] = nums2[n]\n",
    "            n -= 1        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: 'List[int]', m: 'int', nums2: 'List[int]', n: 'int') -> 'None':\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(n):\n",
    "            nums1[m+i]=nums2[i]\n",
    "        nums1.sort()\n",
    "            \n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1, m, nums2, n):\n",
    "        \"\"\"\n",
    "        :type nums1: List[int]\n",
    "        :type m: int\n",
    "        :type nums2: List[int]\n",
    "        :type n: int\n",
    "        :rtype: void Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        i, j, w = m - 1, n - 1, m + n - 1\n",
    "        while i >= 0 and j >= 0:\n",
    "            if nums1[i] >= nums2[j]:\n",
    "                nums1[w] = nums1[i]\n",
    "                w, i = w - 1, i - 1\n",
    "            else:\n",
    "                nums1[w] = nums2[j]\n",
    "                w, j = w - 1, j - 1\n",
    "        while j >= 0:\n",
    "            nums1[w] = nums2[j]\n",
    "            w, j = w - 1, j - 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1, m, nums2, n):\n",
    "        \"\"\"\n",
    "        :type nums1: List[int]\n",
    "        :type m: int\n",
    "        :type nums2: List[int]\n",
    "        :type n: int\n",
    "        :rtype: void Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        if nums1 == [0]:\n",
    "            for i in range (len(nums2)):\n",
    "                nums1[i] = nums2[i]\n",
    "        else:\n",
    "            index1 = 0\n",
    "            for i in range (len(nums2)):\n",
    "                print(i)\n",
    "                while nums2[i] > nums1[index1] and index1 < m:\n",
    "                    index1 = index1 + 1\n",
    "\n",
    "\n",
    "                nums1.insert(index1, nums2[i])\n",
    "                nums1.pop()\n",
    "            nums1.sort()\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1, m, nums2, n):\n",
    "        \"\"\"\n",
    "        :type nums1: List[int]\n",
    "        :type m: int\n",
    "        :type nums2: List[int]\n",
    "        :type n: int\n",
    "        :rtype: void Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        i,j,k=m-1,n-1,m+n-1\n",
    "        \n",
    "        while i>=0 and j>=0:\n",
    "            if nums1[i]>=nums2[j]:\n",
    "                nums1[k]=nums1[i]\n",
    "                i-=1\n",
    "                k-=1\n",
    "            else:\n",
    "                nums1[k]=nums2[j]\n",
    "                j-=1\n",
    "                k-=1\n",
    "        \n",
    "        if j>=0:\n",
    "            nums1[0:j+1]=nums2[0:j+1]\n",
    "            \n",
    "        return\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        nums1[m:] = nums2\n",
    "        nums1.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1, m, nums2, n):\n",
    "        \"\"\"\n",
    "        :type nums1: List[int]\n",
    "        :type m: int\n",
    "        :type nums2: List[int]\n",
    "        :type n: int\n",
    "        :rtype: void Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        def sortnum(nums, left, right):\n",
    "            if left >= right:\n",
    "                return\n",
    "            i = left\n",
    "            j = right\n",
    "            key = nums[left]\n",
    "            while i < j:\n",
    "                while (key <= nums[j] and i < j):\n",
    "                    j = j - 1\n",
    "                print(j)\n",
    "                nums[i] = nums[j]\n",
    "                while (key >= nums[i] and i < j):\n",
    "                    i = i + 1\n",
    "                nums[j] = nums[i]\n",
    "            nums[i] = key\n",
    "            sortnum(nums, left, i-1)\n",
    "            sortnum(nums, i+1, right)\n",
    "        nums1[m:] = nums2      \n",
    "        sortnum(nums1, 0, m+n-1)\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: 'List[int]', m: 'int', nums2: 'List[int]', n: 'int') -> 'None':\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        i = -1\n",
    "        if m == 0:\n",
    "            for a in range(n):\n",
    "                nums1[a] = nums2[a]\n",
    "        elif m*n != 0:\n",
    "            while m*n != 0:\n",
    "                if nums2[n-1] > nums1[m-1]:\n",
    "                    nums1[i] = nums2[n-1]\n",
    "                    n -= 1\n",
    "                else:\n",
    "                    nums1[i] = nums1[m-1]\n",
    "                    m -= 1\n",
    "                i -= 1\n",
    "                if m == 0:\n",
    "                    for r in range(n):\n",
    "                        nums1[r] = nums2[r]\n",
    "                    break\n",
    "                elif n == 0:\n",
    "                    break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        list_merge = nums1[0:m]+nums2[0:n]\n",
    "        list_merge.sort()\n",
    "        for i in range(len(list_merge)):\n",
    "            nums1[i] = list_merge[i]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        end = m + n - 1\n",
    "        m -= 1\n",
    "        n -= 1\n",
    "        while m >= 0 and n >= 0:\n",
    "            if nums1[m] > nums2[n]:\n",
    "                nums1[end] = nums1[m]\n",
    "                m -= 1\n",
    "            else:\n",
    "                nums1[end] = nums2[n]\n",
    "                n -= 1\n",
    "            end -= 1\n",
    "\n",
    "        while n >= 0:\n",
    "            nums1[end] = nums2[n]\n",
    "            end -= 1\n",
    "            n -= 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        # if n == 0:\n",
    "        #     return nums1\n",
    "        # if m == 0:\n",
    "        #     return nums2\n",
    "        \n",
    "        p, p1, p2 = m + n - 1, m - 1, n - 1\n",
    "        while p1 >= 0 and p2 >= 0:\n",
    "            if nums2[p2] >= nums1[p1]:\n",
    "                nums1[p] = nums2[p2]\n",
    "                p2 -= 1\n",
    "            else:\n",
    "                nums1[p] = nums1[p1]\n",
    "                p1 -= 1\n",
    "            p -= 1\n",
    "        \n",
    "        nums1[:p2+1] = nums2[:p2+1]\n",
    "        return nums1\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\r\n",
    "        \"\"\"\r\n",
    "        Do not return anything, modify nums1 in-place instead.\r\n",
    "        \"\"\"\r\n",
    "        nums1[m:m+n] = nums2\r\n",
    "        return nums1.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        ind1= m-1\n",
    "        ind2 = n-1\n",
    "        cur= m+n-1\n",
    "        while  ind1>-1 and ind2>-1:\n",
    "            if nums1[ind1]<nums2[ind2]:\n",
    "                nums1[cur] = nums2[ind2]\n",
    "                ind2= ind2-1\n",
    "                cur= cur-1\n",
    "            else:\n",
    "                nums1[cur] = nums1[ind1]\n",
    "                ind1 = ind1 -1\n",
    "                cur = cur-1\n",
    "        if ind2>-1:\n",
    "            nums1[:ind2+1] = nums2[:ind2+1]\n",
    "        return nums1\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        p1 = m - 1\n",
    "        p2 = n - 1\n",
    "        p = n + m - 1\n",
    "        while p1 >= 0 and p2 >= 0:\n",
    "            if nums1[p1] > nums2[p2]:\n",
    "                nums1[p] = nums1[p1]\n",
    "                p1 -= 1\n",
    "            else:\n",
    "                nums1[p] = nums2[p2]\n",
    "                p2 -= 1\n",
    "            p -= 1\n",
    "        nums1[:p2 + 1] = nums2[:p2 + 1]\n",
    "        return nums1 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "       \n",
    "        for i in range(n):\n",
    "            nums1[m+i]=nums2[i]\n",
    "        \n",
    "        print(nums1.sort())\n",
    " \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        p1, p2 = m-1, n-1\n",
    "        p = m+n-1\n",
    "        while p1 >= 0 and p2 >= 0:\n",
    "            if nums1[p1] > nums2[p2]:\n",
    "                nums1[p] = nums1[p1]\n",
    "                p1 -= 1\n",
    "            else:\n",
    "                nums1[p] = nums2[p2]\n",
    "                p2 -= 1\n",
    "            p -= 1\n",
    "        if p2 >= 0:\n",
    "            for i in range(p2+1):\n",
    "                nums1[i] = nums2[i]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        p = m+n-1\n",
    "        p1 = m-1\n",
    "        p2 = n-1\n",
    "        while p1>=0 and p2>=0:\n",
    "            print(p,p1,p2)\n",
    "            if nums1[p1] > nums2[p2]:\n",
    "                nums1[p] = nums1[p1]\n",
    "                p1 -= 1\n",
    "            else:\n",
    "                nums1[p] = nums2[p2]\n",
    "                p2 -= 1\n",
    "            print(nums1[p])\n",
    "            p -= 1\n",
    "        if p2 >= 0:\n",
    "            nums1[:p2+1] = nums2[:p2+1]\n",
    "                \n",
    "                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        i, j = m-1, n-1\n",
    "        l = m+n\n",
    "        for k in range(l-1, -1, -1):\n",
    "            print(k, i, j)\n",
    "            if i>=0 and j >= 0:\n",
    "                if nums1[i] >= nums2[j]:\n",
    "                    nums1[k] = nums1[i]\n",
    "                    i -= 1\n",
    "                else:\n",
    "                    nums1[k] = nums2[j]\n",
    "                    j -= 1\n",
    "            elif i>=0:\n",
    "                nums1[k] = nums1[i]\n",
    "                i -= 1\n",
    "            elif j >= 0:\n",
    "                nums1[k] = nums2[j]\n",
    "                j -= 1\n",
    "            else:\n",
    "                return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        i, j = 0, 0\n",
    "        cm = m\n",
    "        ic, jc = 0, 0\n",
    "        while ic < m and jc < n:\n",
    "            \n",
    "            if nums1[i] <= nums2[j]:\n",
    "                i += 1\n",
    "                ic += 1\n",
    "                continue\n",
    "            else:\n",
    "                \n",
    "                prev = nums1[i]\n",
    "                \n",
    "                \n",
    "                for k in range(m + n - 1, i, -1):\n",
    "                    print(nums1[k], nums1[k-1])\n",
    "                    nums1[k] = nums1[k- 1]\n",
    "                    \n",
    "                    \n",
    "                    \n",
    "                \n",
    "                nums1[i] = nums2[j]\n",
    "                \n",
    "                i = i + 1\n",
    "                cm += 1\n",
    "                j += 1\n",
    "                jc += 1\n",
    "        \n",
    "        if ic == m:\n",
    "            \n",
    "            nums1[i:] = nums2[j:]\n",
    "        \n",
    "            \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(n):\n",
    "            nums1[m+i] = nums2[i]\n",
    "        return nums1.sort()\n",
    "        # nums = nums1[0:m]+nums2\n",
    "        # nums.sort()\n",
    "        # return nums\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        for index, i in enumerate(nums2):\n",
    "            nums1[m+index] = i\n",
    "        nums1.sort() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        # 题解算法\n",
    "        m,cur,n = m-1,m+n-1,n-1  \n",
    "        while(n>=0):\n",
    "            while m>=0 and nums1[m]>nums2[n]:\n",
    "                nums1[cur]=nums1[m]\n",
    "                cur-=1\n",
    "                m-=1\n",
    "            nums1[cur]=nums2[n]\n",
    "            cur-=1\n",
    "            n-=1\n",
    "        '''我的算法：\n",
    "        length = m+n\n",
    "        if not m:  # nums1为空\n",
    "            for i in range(n):\n",
    "                nums1[i] = nums2[i]\n",
    "        elif not n:  # nums2为空\n",
    "            pass\n",
    "        else:\n",
    "            # 分别指向nums1尾部,nums1最大,nums2的尾部\n",
    "            i,cur,j = m-1,m+n-1,n-1  \n",
    "            while(i<cur):\n",
    "                print(cur,i,j)\n",
    "                if(nums1[i]>nums2[j]):\n",
    "                    nums1[cur]=nums1[i]\n",
    "                    nums1[i]=-1e9-1\n",
    "                    if i:\n",
    "                        i=i-1\n",
    "                else:\n",
    "                    nums1[cur]=nums2[j]\n",
    "                    if j:\n",
    "                        j=j-1\n",
    "                cur-=1\n",
    "            if not nums1[0] or nums1[0]==-1e9-1:\n",
    "                nums1[0]=nums2[0]\n",
    "        '''\n",
    "            \n",
    "\n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        if not nums1: return nums2\n",
    "        if not nums2: return nums1\n",
    "        \n",
    "        nums1[m:] = nums2\n",
    "        nums1.sort()\n",
    "        return nums1\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        length = m+n\n",
    "        if not m:  # nums1为空\n",
    "            for i in range(n):\n",
    "                nums1[i] = nums2[i]\n",
    "        elif not n:  # nums2为空\n",
    "            pass\n",
    "        else:\n",
    "            # 分别指向nums1尾部,nums1最大,nums2的尾部\n",
    "            i,cur,j = m-1,m+n-1,n-1  \n",
    "            while(i<cur):\n",
    "                print(cur,i,j)\n",
    "                if(nums1[i]>nums2[j]):\n",
    "                    nums1[cur]=nums1[i]\n",
    "                    nums1[i]=-1e9-1\n",
    "                    if i:\n",
    "                        i=i-1\n",
    "                else:\n",
    "                    nums1[cur]=nums2[j]\n",
    "                    if j:\n",
    "                        j=j-1\n",
    "                cur-=1\n",
    "            if not nums1[0] or nums1[0]==-1e9-1:\n",
    "                nums1[0]=nums2[0]\n",
    "            \n",
    "\n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        cur_nums1_index = 0\n",
    "        merge_count = 0\n",
    "        for i in range(n):\n",
    "            while nums2[i] > nums1[cur_nums1_index] and cur_nums1_index<m+merge_count :\n",
    "                cur_nums1_index+=1\n",
    "            \n",
    "            if nums1[cur_nums1_index] == 0 and cur_nums1_index>=m+merge_count:\n",
    "                nums1[cur_nums1_index] = nums2[i]\n",
    "                print('触发元素替换:{},原位置代替'.format(nums1))\n",
    "                cur_nums1_index+=1\n",
    "                merge_count+=1\n",
    "                continue\n",
    "\n",
    "            if nums2[i] <= nums1[cur_nums1_index]:\n",
    "                self.move_nums1(cur_nums1_index,m+merge_count,nums1)\n",
    "                nums1[cur_nums1_index] = nums2[i]\n",
    "                print('触发元素替换:{},插入代替'.format(nums1))\n",
    "                cur_nums1_index+=1\n",
    "                merge_count+=1\n",
    "        return nums1\n",
    "\n",
    "    def move_nums1(self,cur_nums1_index,new_len,nums1):\n",
    "        move_index = new_len - 1\n",
    "        for i in range(cur_nums1_index,new_len):\n",
    "            nums1[move_index+1] = nums1[move_index]\n",
    "            move_index -= 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        nums1[m:] = nums2\n",
    "        nums1.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        nums1[m:] = nums2\n",
    "        nums1.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify nums1 in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(n):\n",
    "            nums1[m+i] = nums2[i]\n",
    "        nums1.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeAlternately(self, word1: str, word2: str) -> str:\n",
    "        \"\"\"\n",
    "        len_word1 = len(word1)\n",
    "        len_word2 = len(word2)\n",
    "        curr_word1 = 0\n",
    "        curr_word2 = 0\n",
    "        rst = \"\"\n",
    "        while curr_word1 < len_word1 or curr_word2 < len_word2:\n",
    "            if curr_word1 < len_word1:\n",
    "                rst += word1[curr_word1]\n",
    "                curr_word1 += 1\n",
    "            else:\n",
    "                rst += word2[curr_word2:]\n",
    "                break\n",
    "            if curr_word2 < len_word2:\n",
    "                rst += word2[curr_word2]\n",
    "                curr_word2 += 1\n",
    "            else:\n",
    "                rst  += word1[curr_word1:]\n",
    "                break\n",
    "\n",
    "        return rst\n",
    "        \"\"\"\n",
    "        \n",
    "        \"\"\"\n",
    "        :type word1: str\n",
    "        :type word2: str\n",
    "        :rtype: str\n",
    "        \"\"\"\n",
    "        result = []\n",
    "        i = 0\n",
    "        while i < len(word1) or i < len(word2):\n",
    "            if i < len(word1):\n",
    "                result.append(word1[i])\n",
    "            else: \n",
    "                result.append(word2[i:])\n",
    "                break\n",
    "            if i < len(word2):\n",
    "                result.append(word2[i])\n",
    "            else:\n",
    "                result.append(word1[i+1:])\n",
    "                break\n",
    "            i += 1\n",
    "        return ''.join(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeAlternately(self, word1: str, word2: str) -> str:\n",
    "        index = 0\n",
    "        res = ''\n",
    "        while index <len(word1) or index < len(word2):\n",
    "            if index < len(word1):\n",
    "                res += word1[index]\n",
    "            if index < len(word2):\n",
    "                res += word2[index]\n",
    "            index +=1\n",
    "\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeAlternately(self, word1: str, word2: str) -> str:\n",
    "        return \"\".join([str(word1[i])+str(word2[i]) for i in range(min(len(word1),len(word2)))])+word1[min(len(word1),len(word2)):]+word2[min(len(word1),len(word2)):]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeAlternately(self, word1: str, word2: str) -> str:\n",
    "        index = 0\n",
    "        res = ''\n",
    "        while index < len(word1) or index < len(word2):\n",
    "            if index < len(word1):\n",
    "                res += word1[index]\n",
    "            if index < len(word2):\n",
    "                res += word2[index]\n",
    "            index += 1\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeAlternately(self, word1: str, word2: str) -> str:\n",
    "        res = []\n",
    "        #print(res)\n",
    "        word1 = list(word1)\n",
    "        print(word1)\n",
    "        word2 = list(word2)\n",
    "        print(word2)\n",
    "        while len(word1)>0 and len(word2) >0:\n",
    "            w1 = word1.pop(0)\n",
    "            w2 = word2.pop(0)\n",
    "            res.append(w1)\n",
    "            res.append(w2)\n",
    "            if len(word1) == 0:\n",
    "                res += word2\n",
    "            if len(word2) == 0:\n",
    "                res += word1\n",
    "        print(res)\n",
    "        res = ''.join(res)\n",
    "        print(res)\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeAlternately(self, word1: str, word2: str) -> str:\n",
    "        new_word = [-1 for _ in range(len(word1)+len(word2))]\n",
    "        for i in range(0, min(len(word1), len(word2))):\n",
    "            print(i)\n",
    "            new_word[i*2] = word1[i]\n",
    "            new_word[i*2+1] = word2[i]\n",
    "        res = word1 if len(word1) >= len(word2) else word2\n",
    "        res_n = max(len(word1), len(word2)) - min(len(word1), len(word2))\n",
    "        for i in range(-1, -res_n-1, -1):\n",
    "            new_word[i] = res[i]\n",
    "        return ''.join(new_word)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeAlternately(self, word1: str, word2: str) -> str:\n",
    "        if len(word1) > len(word2):\n",
    "            mergeWord = ''\n",
    "            for i in range(len(word2)):\n",
    "                mergeWord += word1[i] + word2[i]\n",
    "            mergeWord += word1[len(word2):]\n",
    "        else:\n",
    "            mergeWord = ''\n",
    "            for i in range(len(word1)):\n",
    "                mergeWord += word1[i] + word2[i]\n",
    "            mergeWord += word2[len(word1):]\n",
    "        return mergeWord"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeAlternately(self, word1: str, word2: str) -> str:\n",
    "        m, n = len(word1), len(word2)\n",
    "        i = j = 0\n",
    "        ans = list()\n",
    "        while i < m and j < n:\n",
    "            ans.append(word1[i])\n",
    "            ans.append(word2[j])\n",
    "            i+=1\n",
    "            j+=1\n",
    "        ans = \"\".join(ans)\n",
    "        ans = ans + word1[i:] + word2[j:]\n",
    "        return ans\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeAlternately(self, word1: str, word2: str) -> str:\n",
    "        m ,n = len(word1),len(word2)\n",
    "        i,j =0,0\n",
    "        ans = list()\n",
    "        while i <m or j <n :\n",
    "            if i <m :\n",
    "                ans.append(word1[i])\n",
    "                i+=1\n",
    "            if j <n:\n",
    "                ans.append(word2[j])\n",
    "                j+=1\n",
    "        return \"\".join(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        # given [a1,b1,c1] and [a2,b2,c2], and target is [a,b,c]\n",
    "        # if a1 = a, and b2 = b\n",
    "        # we can only successfully merge if b1 <= b, c1 <= c, and a2 <= a, c2 <= c\n",
    "        # if other words, in a triplet, other than the matching element\n",
    "        # all other elements need to be less than or equal to the target\n",
    "\n",
    "        # Implementation wise, we can have an list of length 3 that will give us the final answer\n",
    "        \n",
    "        a, b, c = target\n",
    "        l = [False] * 3\n",
    "        for a1, b1, c1 in triplets:\n",
    "            if a1 <= a and b1 <= b and c1 <= c:\n",
    "                if a1 == a:\n",
    "                    l[0] = True\n",
    "                if b1 == b:\n",
    "                    l[1] = True\n",
    "                if c1 == c:\n",
    "                    l[2] = True\n",
    "            # pre terminate when target can be obtained\n",
    "            if l[0] and l[1] and l[2]:\n",
    "                return True\n",
    "        \n",
    "        return l[0] and l[1] and l[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x, y, z = target\n",
    "        a, b, c = 0, 0, 0\n",
    "\n",
    "        for ai, bi, ci, in triplets:\n",
    "            if ai <= x and bi <= y and ci <= z:\n",
    "                a, b, c = max(a, ai), max(b, bi), max(c, ci)\n",
    "\n",
    "        return (a, b, c) == (x, y, z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x,y,z = target\n",
    "        a,b,c = 0,0,0\n",
    "        for ai,bi,ci in triplets:\n",
    "            if ai <= x and bi <= y and ci <= z:\n",
    "                a,b,c = max(a,ai),max(b,bi),max(c,ci)\n",
    "        return (a,b,c) == (x,y,z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x, y, z = target\n",
    "        a, b, c = 0, 0, 0\n",
    "\n",
    "        for u, v, w in triplets:\n",
    "            if u <= x and v <= y and w <= z:\n",
    "                a, b, c = max(a, u), max(b, v), max(c, w)\n",
    "\n",
    "        return (a, b, c) == (x, y, z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        a = b = c = False\n",
    "        for x, y, z in triplets:\n",
    "            if not a and x == target[0] and y <= target[1] and z <= target[2]:\n",
    "                a = True\n",
    "            if not b and y == target[1] and x <= target[0] and z <= target[2]:\n",
    "                b = True\n",
    "            if not c and z == target[2] and x <= target[0] and y <= target[1]:\n",
    "                c = True\n",
    "            if a and b and c:\n",
    "                return True\n",
    "        return False\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        # # 执行操作只会让数变大/不变，所以应该选择满足all(triplet[i]<=target[i] for i in range(3))的三元组进行合并\n",
    "        # if not all(t <= tg for t,tg in zip(triplets[0], target)):\n",
    "        #     triplets[0] = [0,0,0]\n",
    "        # for ai, bi, ci in triplets:\n",
    "        #     if ai<=target[0] and bi<=target[1] and ci<=target[2]:\n",
    "        #         triplets[0][0], triplets[0][1], triplets[0][2] = max(triplets[0][0],ai), max(triplets[0][1],bi), max(triplets[0][2],ci)\n",
    "        # return triplets[0]==target\n",
    "\n",
    "        # 只要对于满足all(triplet[i]<=target[i] for i in range(3))的三元组，各部分都出现了x,y,z，则能够更新为xyz\n",
    "        found = [False] * 3\n",
    "        for ai,bi,ci in triplets:\n",
    "            if ai<=target[0] and bi<=target[1] and ci<=target[2]:\n",
    "                found[0] = found[0] or ai == target[0]\n",
    "                found[1] = found[1] or bi == target[1]\n",
    "                found[2] = found[2] or ci == target[2]\n",
    "        return all(found)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x, y, z = target\n",
    "        a, b, c = 0, 0, 0\n",
    "\n",
    "        for u, v, w in triplets:\n",
    "            if u > x or v > y or w > z: continue\n",
    "            a, b, c = max(a, u), max(b, v), max(c, w)\n",
    "            if (a, b, c) == (x, y, z): return True\n",
    "\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\r\n",
    "        # for n in range(len(triplets)):\r\n",
    "            # if triplets[n].count\r\n",
    "        # for n in target:\r\n",
    "        #     if triplets.count(n)==0:\r\n",
    "        #         return False\r\n",
    "        x,y,z = target\r\n",
    "        x_ = y_ = z_ = False\r\n",
    "        for a,b,c in list(triplets):\r\n",
    "            if a > x or b > y or c > z:\r\n",
    "                continue\r\n",
    "            if a == x:\r\n",
    "                x_ = True\r\n",
    "            if b == y:\r\n",
    "                y_ = True\r\n",
    "            if c == z:\r\n",
    "                z_ = True\r\n",
    "        return x_ and y_ and z_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        found = [0, 0, 0]\n",
    "        for t in triplets:\n",
    "            state = [-1 if i[0] < i[1] else (0 if i[0] == i[1] else 1) for i in zip(t, target)]\n",
    "            if 1 in state:\n",
    "                continue\n",
    "            for i in range(3):\n",
    "                found[i] = 1 if found[i] > 0 or state[i] == 0 else 0\n",
    "            if found == [1, 1, 1]:\n",
    "                return True\n",
    "        return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        a, b, c = target\n",
    "\n",
    "        x = y = z = 0\n",
    "        for i, j, k in triplets:\n",
    "            if i<=a and j<=b and k<=c:\n",
    "                x, y, z = max(x, i), max(y, j), max(z, k)\n",
    "        \n",
    "        return (a, b, c) == (x, y, z)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        flag1 = flag2 = flag3 = False;\n",
    "\n",
    "        for x, y, z in triplets:\n",
    "            if x == target[0] and y <= target[1] and z <= target[2]:\n",
    "                flag1 = True\n",
    "            if x <= target[0] and y == target[1] and z <= target[2]:\n",
    "                flag2 = True\n",
    "            if x <= target[0] and y <= target[1] and z == target[2]:\n",
    "                flag3 = True\n",
    "        \n",
    "        return flag1 and flag2 and flag3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        found = [False] * 3\n",
    "        for t in triplets:\n",
    "            if t[0] <= target[0] and t[1] <= target[1] and t[2] <= target[2]:\n",
    "                found[0] = found[0] or t[0] == target[0]\n",
    "                found[1] = found[1] or t[1] == target[1]\n",
    "                found[2] = found[2] or t[2] == target[2]\n",
    "        return all(found)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        candidates = []\n",
    "        idx = [False, False, False]\n",
    "\n",
    "        for triplet in triplets:\n",
    "            if all(triplet[i] <= target[i] for i in range(3)):\n",
    "                candidates.append(triplet)\n",
    "                \n",
    "                for i in range(3):\n",
    "                    if triplet[i] == target[i]:\n",
    "                        idx[i] = True\n",
    "\n",
    "        return len(candidates) > 0 and all(idx)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        check = [False] * 3\n",
    "        i = 0\n",
    "        while i < len(triplets) and not (check[0] and check[1] and check[2]):\n",
    "            t = triplets[i]\n",
    "            if target[0] >= t[0] and target[1] >= t[1] and target[2] >= t[2]:\n",
    "                if target[0] == t[0]:\n",
    "                    check[0] = True\n",
    "                if target[1] == t[1]:\n",
    "                    check[1] = True\n",
    "                if target[2] == t[2]:\n",
    "                    check[2] = True\n",
    "            i += 1\n",
    "        \n",
    "        return check[0] and check[1] and check[2] \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "def max_(a, b):\n",
    "    return a if a > b else b\n",
    "\n",
    "\n",
    "def min_(a, b):\n",
    "    return a if a < b else b\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        a, b, c = target[:]\n",
    "        x = y = z = 0\n",
    "        for x0, y0, z0 in triplets:\n",
    "            if x0<=a and y0<=b and z0<=c:\n",
    "                x = max_(x, x0)\n",
    "                y = max_(y, y0)\n",
    "                z = max_(z, z0)\n",
    "        return x == a and y == b and z == c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        # 只要3个数都小于等于目标，就可以加入\n",
    "        cur = [0] * 3\n",
    "        for a, b, c in triplets:\n",
    "            if a <= target[0] and b <= target[1] and c <= target[2]:\n",
    "                cur[0] = max(cur[0], a)\n",
    "                cur[1] = max(cur[1], b)\n",
    "                cur[2] = max(cur[2], c)\n",
    "                if cur == target:\n",
    "                    return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        a = b = c = -1\n",
    "        for x, y, z in triplets:\n",
    "            if x <= target[0] and y <= target[1] and z <= target[2]:\n",
    "                a = max(a, x)\n",
    "                b = max(b, y)\n",
    "                c = max(c, z)\n",
    "        if target[0] == a and target[1] == b and target[2] == c:\n",
    "            return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        for i in range(3):\n",
    "            s = {0, 1, 2} - {i}\n",
    "            for tr in triplets:\n",
    "                if tr[i] != target[i]:\n",
    "                    continue\n",
    "                for j in s:\n",
    "                    if tr[j] > target[j]:\n",
    "                        break\n",
    "                else:\n",
    "                    break\n",
    "            else:\n",
    "                return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        if target in triplets:\n",
    "            return True\n",
    "        else:\n",
    "            x,y,z=target\n",
    "            x_=y_=z_=False\n",
    "            for a,b,c in list(triplets):\n",
    "                if a>x or b>y or c>z:\n",
    "                    continue\n",
    "                if a==x:\n",
    "                    x_=True\n",
    "                if b==y:\n",
    "                    y_=True\n",
    "                if c==z:\n",
    "                    z_=True\n",
    "        return x_ and y_ and z_\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        lookup = [False, False, False]\n",
    "        for triplet in triplets:\n",
    "            cur_lookup = [False, False, False]\n",
    "            addable = True\n",
    "            for i in range(3):\n",
    "                if triplet[i] > target[i]:\n",
    "                    addable = False\n",
    "                    break\n",
    "                elif triplet[i] == target[i]:\n",
    "                    cur_lookup[i] = True\n",
    "            if addable:\n",
    "                for i in range(len(cur_lookup)):\n",
    "                    if cur_lookup[i]:\n",
    "                        lookup[i] = cur_lookup[i]\n",
    "        for val in lookup:\n",
    "            if not val:\n",
    "                return False\n",
    "        return True\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        cur_max = [0,0,0]\n",
    "        for a,b,c in triplets:\n",
    "            if a > target[0] or b > target[1] or c > target[2]:\n",
    "                continue\n",
    "            else:\n",
    "                cur_max[0] = max(cur_max[0], a)\n",
    "                cur_max[1] = max(cur_max[1], b)\n",
    "                cur_max[2] = max(cur_max[2], c)\n",
    "        return cur_max == target\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x,y,z = target\n",
    "        x_ = y_ = z_ = False\n",
    "        for a,b,c in list(triplets):\n",
    "            if a > x or b > y or c > z:\n",
    "                continue\n",
    "            if a == x:\n",
    "                x_ = True\n",
    "            if b == y:\n",
    "                y_ = True\n",
    "            if c == z:\n",
    "                z_ = True\n",
    "        return x_ and y_ and z_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        if len(triplets) == 1:\n",
    "            return target == triplets[0]\n",
    "        res = [-float(\"inf\"), -float(\"inf\"), -float(\"inf\")]\n",
    "        for tri in triplets:\n",
    "            if tri[0] > target[0] or tri[1] > target[1] or tri[2] > target[2]:\n",
    "                print(tri, \"no\")\n",
    "                continue\n",
    "            else:\n",
    "                res = [max(tri[0], res[0]), max(tri[1], res[1]), max(tri[2], res[2])]\n",
    "                print(res, \"new\")\n",
    "        return res == target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x,y,z = target\n",
    "        x_ = y_ = z_ = False\n",
    "        for a,b,c in list(triplets):\n",
    "            if a > x or b > y or c > z:\n",
    "                continue\n",
    "            if a == x:\n",
    "                x_ = True\n",
    "            if b == y:\n",
    "                y_ = True\n",
    "            if c == z:\n",
    "                z_ = True\n",
    "        return x_ and y_ and z_\n",
    "\n",
    "\n",
    "        # queue = list()\n",
    "        # for x,y,z in triplets:\n",
    "        #     #他们中是否有等于三位数中一个的\n",
    "        #     if x!=target[0] and y!=target[1] and z!=target[2]:\n",
    "        #         continue\n",
    "        #     #其他不等的是否不大于目标数\n",
    "        #     if x>target[0] or y>target[1] or z>target[2]:\n",
    "        #         continue\n",
    "        #     queue.append([x,y,z])\n",
    "        # if len(queue) == 0:\n",
    "        #     return False\n",
    "        # tracker = [False]*3\n",
    "        # x,y,z = queue[0]\n",
    "        # for i in range(1,len(queue)):\n",
    "        #     w,h,l = queue[i]\n",
    "        #     x = max(x,w)\n",
    "        #     y = max(y,h)\n",
    "        #     z = max(z,l)\n",
    "        \n",
    "        # if [x,y,z] != target:\n",
    "        #     return False\n",
    "        # return True\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "\n",
    "        is_find = [False for _ in range(3)]\n",
    "\n",
    "        for (a,b,c) in triplets:\n",
    "            if (a == target[0] or b == target[1] or c == target[2]) and a <= target[0] and b <= target[1] and c <= target[2]:\n",
    "                if a == target[0]:\n",
    "                    is_find[0] = True\n",
    "                if b == target[1]:\n",
    "                    is_find[1] = True\n",
    "                if c == target[2]:\n",
    "                    is_find[2] = True\n",
    "        \n",
    "        if is_find[0] and is_find[1] and is_find[2]:\n",
    "            return True\n",
    "        else:\n",
    "            return False\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        s = {0,1,2}\n",
    "        for x, y, z in triplets:\n",
    "            if x > target[0] or y > target[1] or z > target[2]:\n",
    "                continue\n",
    "            if x == target[0] and 0 in s:\n",
    "                s.remove(0)\n",
    "            if y == target[1] and 1 in s:\n",
    "                s.remove(1)\n",
    "            if z == target[2] and 2 in s:\n",
    "                s.remove(2)\n",
    "        return len(s) == 0 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        max_a = 0\n",
    "        max_b = 0\n",
    "        max_c = 0\n",
    "        for i in range(0, len(triplets)):\n",
    "            row = triplets[i]\n",
    "            a = row[0]\n",
    "            b = row[1]\n",
    "            c = row[2]\n",
    "            if a <= target[0] and b <= target[1] and c <= target[2]:\n",
    "                max_a = max(a, max_a)\n",
    "                max_b = max(b, max_b)\n",
    "                max_c = max(c, max_c)\n",
    "        return max_a == target[0] and max_b == target[1] and max_c == target[2]\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        a,b,c = 0,0,0\n",
    "        for triplet in triplets:\n",
    "            if triplet[0]<=target[0] and triplet[1]<=target[1] and triplet[2]<=target[2]:\n",
    "                a=max(a,triplet[0])\n",
    "                b=max(b,triplet[1])\n",
    "                c=max(c,triplet[2])\n",
    "\n",
    "        return a==target[0] and b==target[1] and c==target[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        ans = [0]*3\n",
    "        for a,b,c in triplets:\n",
    "            if a <= target[0] and b <= target[1] and c <= target[2]:\n",
    "                if a == target[0]:\n",
    "                    ans[0] = 1\n",
    "                if b == target[1]:\n",
    "                    ans[1] = 1\n",
    "                if c == target[2]:\n",
    "                    ans[2] = 1\n",
    "        return sum(ans) == 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        flag1 = flag2 = flag3 = False\n",
    "        for t in triplets:\n",
    "            if t[0] == target[0] and t[1] <= target[1] and t[2] <= target[2]:\n",
    "                flag1 = True\n",
    "            if t[1] == target[1] and t[0] <= target[0] and t[2] <= target[2]:\n",
    "                flag2 = True\n",
    "            if t[2] == target[2] and t[0] <= target[0] and t[1] <= target[1]:\n",
    "                flag3 = True\n",
    "        return flag1 and flag2 and flag3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        t = [0,0,0]\n",
    "        for i,j,k in triplets:\n",
    "            if i<=target[0] and j<= target[1] and k<= target[2]:\n",
    "                t[0] = max(t[0],i)\n",
    "                t[1] = max(t[1],j)\n",
    "                t[2] = max(t[2],k)\n",
    "        return t==target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        check = [False] * 3\n",
    "        i = 0\n",
    "        while i < len(triplets) and not (check[0] and check[1] and check[2]):\n",
    "            t = triplets[i]\n",
    "            if target[0] >= t[0] and target[1] >= t[1] and target[2] >= t[2]:\n",
    "              for index, value in enumerate(t):\n",
    "                if target[index] == t[index]:\n",
    "                  check[index] = True\n",
    "            i += 1\n",
    "        \n",
    "        return check[0] and check[1] and check[2] \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        cnt = defaultdict(list)\n",
    "        for t in triplets:\n",
    "            if t == target:\n",
    "                return True\n",
    "            if t[0] == target[0]:\n",
    "                cnt[0].append(t)\n",
    "            if t[1] == target[1]:\n",
    "                cnt[1].append(t)\n",
    "            if t[2] == target[2]:\n",
    "                cnt[2].append(t) \n",
    "        ret = 0\n",
    "        for v in cnt.values():\n",
    "            for t in v:\n",
    "                if all(x <= y for x, y in zip(t, target)):\n",
    "                    ret += 1\n",
    "                    break\n",
    "        return ret >= 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        cnt = defaultdict(list)\n",
    "        for t in triplets:\n",
    "            if t == target:\n",
    "                return True\n",
    "            if all(x <= y for x, y in zip(t, target)):\n",
    "                if t[0] == target[0]:\n",
    "                    cnt[0].append(t)\n",
    "                if t[1] == target[1]:\n",
    "                    cnt[1].append(t)\n",
    "                if t[2] == target[2]:\n",
    "                    cnt[2].append(t) \n",
    "        return len(cnt) == 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        flag1 = False\n",
    "        flag2 = False\n",
    "        flag3 = False\n",
    "        for t in triplets:\n",
    "            if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]:\n",
    "                continue\n",
    "            else:\n",
    "                if t[0] == target[0]:\n",
    "                    flag1 = True\n",
    "                if t[1] == target[1]:\n",
    "                    flag2 = True\n",
    "                if t[2] == target[2]:\n",
    "                    flag3 = True \n",
    "        return flag1 and flag2 and flag3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], t: List[int]) -> bool:\n",
    "\n",
    "        i = 0\n",
    "        for x, y, z in triplets:\n",
    "            if x <= t[0] and y <= t[1] and z <= t[2] and (x == t[0] or y == t[1] or z == t[2]):\n",
    "                if x == t[0]:\n",
    "                    i |= 1\n",
    "                if y == t[1]:\n",
    "                    i |= 2\n",
    "                if z == t[2]:\n",
    "                    i |= 4\n",
    "                if i == 7:\n",
    "                    return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        n = len(triplets)\n",
    "        res = [-inf, -inf, -inf]\n",
    "        for i in range(n):\n",
    "            cur = triplets[i]\n",
    "            if cur[0] > target[0] or cur[1] > target[1] or cur[2] > target[2]:\n",
    "                continue \n",
    "            res[0] = max(res[0], cur[0])\n",
    "            res[1] = max(res[1], cur[1])\n",
    "            res[2] = max(res[2], cur[2])\n",
    "        return res == target\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        cnt = defaultdict(list)\n",
    "        n = len(triplets)\n",
    "        for t in triplets:\n",
    "            if t == target:\n",
    "                return True\n",
    "            if t[0] == target[0]:\n",
    "                cnt[0].append(t)\n",
    "            if t[1] == target[1]:\n",
    "                cnt[1].append(t)\n",
    "            if t[2] == target[2]:\n",
    "                cnt[2].append(t) \n",
    "        if len(cnt) < 3: return False\n",
    "        print(cnt)\n",
    "        ret = 0\n",
    "        for v in cnt.values():\n",
    "            for t in v:\n",
    "                if all(x <= y for x, y in zip(t, target)):\n",
    "                    ret += 1\n",
    "                    break\n",
    "        return ret >= 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        a = [0]*3\n",
    "        for l in triplets:\n",
    "            if l[0] == target[0] and l[1] <= target[1] and l[2] <= target[2]:\n",
    "                a[0] = 1\n",
    "            if l[0] <= target[0] and l[1] == target[1] and l[2] <= target[2]:\n",
    "                a[1] = 1\n",
    "            if l[0] <= target[0] and l[1] <= target[1] and l[2] == target[2]:\n",
    "                a[2] = 1\n",
    "            if a == [1,1,1]:\n",
    "                return True\n",
    "        return False\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        filtered_list = []\n",
    "        for elem in triplets:\n",
    "            if elem[0] == target[0] or elem[1] == target[1] or elem[2] == target[2]:\n",
    "                if elem[0] <= target[0] and elem[1] <= target[1] and elem[2] <= target[2]:\n",
    "                    filtered_list.append(elem)\n",
    "        flag = [False, False, False]\n",
    "        for elem in filtered_list:\n",
    "            if elem[0] == target[0]:\n",
    "                flag[0] = True\n",
    "            if elem[1] == target[1]:\n",
    "                flag[1] = True\n",
    "            if elem[2] == target[2]:\n",
    "                flag[2] = True\n",
    "        return flag[0] and flag[1] and flag[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        # 执行操作只会让数变大/不变，所以应该选择满足all(triplet[i]<=target[i] for i in range(3))的三元组进行合并\n",
    "        if not all(t <= tg for t,tg in zip(triplets[0], target)):\n",
    "            triplets[0] = [0,0,0]\n",
    "        for ai, bi, ci in triplets:\n",
    "            if ai<=target[0] and bi<=target[1] and ci<=target[2]:\n",
    "                triplets[0][0], triplets[0][1], triplets[0][2] = max(triplets[0][0],ai), max(triplets[0][1],bi), max(triplets[0][2],ci)\n",
    "        return triplets[0]==target\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x,y,z = target\n",
    "        x_ = y_ = z_ = False\n",
    "        for a,b,c in list(triplets):\n",
    "            if a > x or b > y or c > z:\n",
    "                continue\n",
    "            if a == x:\n",
    "                x_ = True\n",
    "            if b == y:\n",
    "                y_ = True\n",
    "            if c == z:\n",
    "                z_ = True\n",
    "        return x_ and y_ and z_\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        if target in triplets:\n",
    "            return True\n",
    "        else:\n",
    "            x,y,z=target\n",
    "            x_=y_=z_=False\n",
    "            for a,b,c in list(triplets):\n",
    "                if a>x or b>y or c>z:\n",
    "                    continue\n",
    "                if a==x:\n",
    "                    x_=True\n",
    "                if b==y:\n",
    "                    y_=True\n",
    "                if c==z:\n",
    "                    z_=True\n",
    "        return x_ and y_ and z_\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        if target in triplets:\n",
    "            return True\n",
    "        \n",
    "        first = 0\n",
    "        second = 0\n",
    "        third = 0\n",
    "        for t in triplets:\n",
    "            if t[0] == target[0] and t[1] <= target[1] and t[2] <= target[2]:\n",
    "                first = t\n",
    "            if t[1] == target[1] and t[0] <= target[0] and t[2] <= target[2]:\n",
    "                second = t\n",
    "            if t[2] == target[2] and t[1] <= target[1] and t[0] <= target[0]:\n",
    "                third = t\n",
    "        if first == 0 or second == 0 or third == 0:\n",
    "            return False\n",
    "        result = [max(first[0],second[0],third[0]),max(first[1],second[1],third[1]),max(first[2],second[2],third[2])]\n",
    "        print(first,second,third)\n",
    "        return result == target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x,y,z=target\n",
    "        a,b,c=0,0,0\n",
    "\n",
    "        for ai,bi,ci in triplets:\n",
    "            if ai<=x and bi<=y and ci<=z:\n",
    "                a=max(a,ai)\n",
    "                b=max(b,bi)\n",
    "                c=max(c,ci)\n",
    "        \n",
    "        return (a,b,c)==(x,y,z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        # Initialize three variables to keep track of the maximum values for each element in the triplets\n",
    "        max_a, max_b, max_c = 0, 0, 0\n",
    "        \n",
    "        # Iterate through each triplet in the list\n",
    "        for triplet in triplets:\n",
    "            # Check if the current triplet can contribute to the maximum values\n",
    "            if triplet[0] <= target[0] and triplet[1] <= target[1] and triplet[2] <= target[2]:\n",
    "                max_a = max(max_a, triplet[0])\n",
    "                max_b = max(max_b, triplet[1])\n",
    "                max_c = max(max_c, triplet[2])\n",
    "        \n",
    "        # Check if the maximum values match the target triplet\n",
    "        return max_a == target[0] and max_b == target[1] and max_c == target[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        if len(triplets) == 1:\n",
    "            return target == triplets[0]\n",
    "        res = [-float(\"inf\"), -float(\"inf\"), -float(\"inf\")]\n",
    "        for tri in triplets:\n",
    "            if tri[0] > target[0] or tri[1] > target[1] or tri[2] > target[2]:\n",
    "                print(tri, \"no\")\n",
    "                continue\n",
    "            else:\n",
    "                res = [max(tri[0], res[0]), max(tri[1], res[1]), max(tri[2], res[2])]\n",
    "                print(res, \"new\")\n",
    "        return res == target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        judge = [0] * 3\n",
    "        for i in range(0,len(triplets)):\n",
    "            k = triplets[i]\n",
    "            if k[0] == target[0] and k[1] <= target[1] and k[2] <= target[2]:\n",
    "                judge[0] = 1\n",
    "            if k[1] == target[1] and k[2] <= target[2] and k[0] <= target[0]:\n",
    "                judge[1] = 1\n",
    "            if k[2] == target[2] and k[1] <= target[1] and k[0] <= target[0]:\n",
    "                judge[2] = 1\n",
    "        return sum(judge) == 3\n",
    "            \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        s1 = set()\n",
    "        s2 = set()\n",
    "        s3 = set()\n",
    "        for i,(x, y, z) in enumerate(triplets):\n",
    "            if x == target[0] and y <= target[1] and z <= target[2]:\n",
    "                s1.add(i)\n",
    "            if y == target[1] and x <= target[0] and z <= target[2]:\n",
    "                s2.add(i)\n",
    "            if z == target[2] and x <= target[0] and y <= target[1]:\n",
    "                s3.add(i)\n",
    "        return bool(len(s1) and len(s2) and len(s3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x, y, z = target\n",
    "        a, b, c = 0, 0, 0\n",
    "        \n",
    "        for ai, bi, ci in triplets:\n",
    "            if ai <= x and bi <= y and ci <= z:\n",
    "                a, b, c = max(a, ai), max(b, bi), max(c, ci)\n",
    "        \n",
    "        return (a, b, c) == (x, y, z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x, y, z = 0, 0, 0\n",
    "        for t in triplets:\n",
    "            if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]:\n",
    "                continue\n",
    "            x = max(t[0], x)\n",
    "            y = max(t[1],y)\n",
    "            z = max(t[2],z)\n",
    "        return x == target[0] and y == target[1] and z == target[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n",
    "        x,y,z=target\n",
    "        a,b,c=0,0,0\n",
    "\n",
    "        for ai,bi,ci in triplets:\n",
    "            if ai<=x and bi<=y and ci<=z:\n",
    "                a=max(a,ai)\n",
    "                b=max(b,bi)\n",
    "                c=max(c,ci)\n",
    "        \n",
    "        return (a,b,c)==(x,y,z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        index1 = 0\n",
    "        index2 =0\n",
    "        res = []\n",
    "\n",
    "        while index1 < len(nums1) and index2 < len(nums2):\n",
    "            if nums1[index1][0] == nums2[index2][0]:\n",
    "                res.append([nums1[index1][0],nums1[index1][1]+nums2[index2][1]])\n",
    "                index1+=1\n",
    "                index2+=1\n",
    "            elif nums1[index1][0] < nums2[index2][0]:\n",
    "                res.append(nums1[index1])\n",
    "                index1+=1\n",
    "            else:\n",
    "                res.append(nums2[index2])\n",
    "                index2+=1\n",
    "        res+=nums1[index1:]\n",
    "        res+=nums2[index2:]\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]:\n",
    "        ans = []\n",
    "        i, n = 0, len(a)\n",
    "        j, m = 0, len(b)\n",
    "        while True:\n",
    "            if i == n:\n",
    "                ans.extend(b[j:])\n",
    "                return ans\n",
    "            if j == m:\n",
    "                ans.extend(a[i:])\n",
    "                return ans\n",
    "            if a[i][0] < b[j][0]:\n",
    "                ans.append(a[i])\n",
    "                i += 1\n",
    "            elif a[i][0] > b[j][0]:\n",
    "                ans.append(b[j])\n",
    "                j += 1\n",
    "            else:\n",
    "                a[i][1] += b[j][1]\n",
    "                ans.append(a[i])\n",
    "                i += 1\n",
    "                j += 1\n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        i, j = 0, 0\n",
    "        ans = []\n",
    "        n1, n2 = len(nums1), len(nums2)\n",
    "        while i < n1 and j < n2:\n",
    "            num1, num2 = nums1[i][0], nums2[j][0]\n",
    "            if num1 == num2:\n",
    "                ans.append([num1, nums1[i][1]+nums2[j][1]])\n",
    "                i += 1\n",
    "                j += 1\n",
    "            elif num1 > num2:\n",
    "                ans.append([num2, nums2[j][1]])\n",
    "                j += 1\n",
    "            else:\n",
    "                ans.append([num1, nums1[i][1]])\n",
    "                i += 1\n",
    "        while i < n1:\n",
    "            ans.append([nums1[i][0], nums1[i][1]])\n",
    "            i += 1\n",
    "        while j < n2:\n",
    "            ans.append([nums2[j][0], nums2[j][1]])\n",
    "            j += 1\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        d1 = [0] * 1001\n",
    "        for k,v in nums1:\n",
    "            d1[k] += v\n",
    "        for k,v in nums2:\n",
    "            d1[k] += v\n",
    "        # ans = []\n",
    "        # for k,v in enumerate(d1):\n",
    "        #     if v:\n",
    "        #         ans.append([k,v])\n",
    "        return [[k,v] for k,v in enumerate(d1) if v]\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        log = Counter()\n",
    "        for x, y in nums1 + nums2: log[x] += y\n",
    "        return sorted(log.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        c = Counter()\n",
    "        for i, x in nums1:\n",
    "            c[i] = x\n",
    "        for j, y in nums2:\n",
    "            c[j] += y\n",
    "        return sorted([[k, v] for k, v in c.items()])\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        newList = []\n",
    "        while len(nums1) > 0 or len(nums2) > 0:\n",
    "            case = 0\n",
    "            if len(nums2) == 0 and len(nums1) > 0:\n",
    "                case = 1\n",
    "            elif len(nums1) == 0 and len(nums2) > 0:\n",
    "                case = 2\n",
    "            elif nums1[0][0] < nums2[0][0]:\n",
    "                case = 1\n",
    "            elif nums1[0][0] > nums2[0][0]:\n",
    "                case = 2\n",
    "            elif nums1[0][0] == nums2[0][0]:\n",
    "                case = 3\n",
    "\n",
    "            if case == 1:\n",
    "                newList.append(nums1[0])\n",
    "                del nums1[0]\n",
    "            elif case == 2:\n",
    "                newList.append(nums2[0])\n",
    "                del nums2[0]\n",
    "            elif case == 3:\n",
    "                newList.append([nums1[0][0], nums1[0][1] + nums2[0][1]])\n",
    "                del nums1[0]\n",
    "                del nums2[0]\n",
    "        return newList"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        ans = list()\n",
    "        i, j = 0, 0\n",
    "        while i < len(nums1) or j < len(nums2):\n",
    "            if j >= len(nums2):\n",
    "                ans.extend(nums1[i:])\n",
    "                break\n",
    "            if i >= len(nums1):\n",
    "                ans.extend(nums2[j:])\n",
    "                break\n",
    "            if nums1[i][0] < nums2[j][0]:\n",
    "                ans.append(nums1[i])\n",
    "                i += 1\n",
    "            elif nums1[i][0] == nums2[j][0]:\n",
    "                ans.append([nums1[i][0], nums1[i][1] + nums2[j][1]])\n",
    "                i += 1\n",
    "                j += 1\n",
    "            else:\n",
    "                ans.append(nums2[j])\n",
    "                j += 1\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:       \n",
    "        d = Counter()\n",
    "        for x, y in nums1: d[x] += y\n",
    "        for x, y in nums2: d[x] += y\n",
    "        return sorted(d.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        res = {}\n",
    "        nums1.extend(nums2)\n",
    "        for num in nums1:\n",
    "            res[num[0]] = res.get(num[0], 0) + num[1]\n",
    "        return sorted([[key, value] for key, value in res.items()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        count = Counter()\n",
    "        for x, y in nums1 + nums2:\n",
    "            count[x] += y\n",
    "        return sorted(count.items())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        result = []\n",
    "        i, j = 0, 0\n",
    "\n",
    "        while i < len(nums1) or j < len(nums2):\n",
    "            id1 = nums1[i][0] if i < len(nums1) else float('inf')\n",
    "            id2 = nums2[j][0] if j < len(nums2) else float('inf')\n",
    "\n",
    "            if id1 == id2:\n",
    "                result.append([id1, nums1[i][1] + nums2[j][1]])\n",
    "                i += 1\n",
    "                j += 1\n",
    "            elif id1 < id2:\n",
    "                result.append([id1, nums1[i][1]])\n",
    "                i += 1\n",
    "            else:\n",
    "                result.append([id2, nums2[j][1]])\n",
    "                j += 1\n",
    "\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        nums1.extend(nums2)\n",
    "        hash_s = set()\n",
    "        hash_d = {}\n",
    "        for i in nums1:\n",
    "            hash_d[i[0]] = hash_d.get(i[0],0) + i[1]\n",
    "        num = [[k,v] for k, v in hash_d.items()]\n",
    "        return sorted(num,key = lambda x:x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        i = j = 0\n",
    "        rv = []\n",
    "        while i<len(nums1) and j<len(nums2):\n",
    "            p, x = nums1[i]\n",
    "            q, y = nums2[j]\n",
    "            if p==q:\n",
    "                rv.append([p,x+y])\n",
    "                i += 1\n",
    "                j += 1\n",
    "            elif p<q:\n",
    "                rv.append([p,x])\n",
    "                i += 1\n",
    "            else:\n",
    "                rv.append([q,y])\n",
    "                j += 1\n",
    "        while i<len(nums1):\n",
    "            p, x = nums1[i]\n",
    "            rv.append([p,x])\n",
    "            i += 1\n",
    "        while j<len(nums2):\n",
    "            q, y = nums2[j]\n",
    "            rv.append([q,y])\n",
    "            j += 1\n",
    "        return rv "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        m = {}\n",
    "        for xs in nums1:\n",
    "            m[xs[0]] = xs\n",
    "        for xs in nums2:\n",
    "            if xs[0] in m:\n",
    "                m[xs[0]][1] += xs[1]\n",
    "            else:\n",
    "                m[xs[0]] = xs\n",
    "\n",
    "        a=sorted(m)\n",
    "        array = []\n",
    "        for index in a:\n",
    "            array.append(m[index])\n",
    "        return array\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        log = Counter()\n",
    "        for x, y in nums1 + nums2: log[x] += y\n",
    "        return sorted(log.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        nums1.extend(nums2)\n",
    "        hash_d = {}\n",
    "        for i in nums1:\n",
    "            hash_d[i[0]] = hash_d.get(i[0],0) + i[1]\n",
    "        num = [[k,v] for k, v in hash_d.items()]\n",
    "        return sorted(num,key = lambda x:x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        sumDict = defaultdict(int)\n",
    "        for idx, val in nums1 + nums2:\n",
    "            sumDict[idx] += val\n",
    "        return sorted(list(sumDict.items()), key=lambda x:x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        d = {}\n",
    "        for x, y in nums1:\n",
    "            d[x] = y\n",
    "        for x, y in nums2:\n",
    "            d[x] = d.get(x, 0) + y\n",
    "        res = []\n",
    "        for x in d:\n",
    "            res.append([x, d[x]])\n",
    "        res.sort()\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        cnt = {}\n",
    "        for i in range(len(nums1)):\n",
    "            cnt[nums1[i][0]] = nums1[i][1] if nums1[i][0] not in cnt else cnt[nums1[i][0]] + nums1[i][1]\n",
    "        for i in range(len(nums2)):\n",
    "            cnt[nums2[i][0]] = nums2[i][1] if nums2[i][0] not in cnt else cnt[nums2[i][0]] + nums2[i][1]\n",
    "        ans = []\n",
    "        for key, value in cnt.items():\n",
    "            ans.append([key, value])\n",
    "        ans.sort(key=lambda x:x[0])\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        a={i[0]:i[1] for i in nums1}\n",
    "        b={i[0]:i[1] for i in nums2}\n",
    "        for i in a.keys():\n",
    "            if i in b:\n",
    "                b[i]+=a[i]\n",
    "            else:\n",
    "                b[i]=a[i]\n",
    "        b=sorted(b.items(),key=lambda x:x[0])\n",
    "        return [list(i) for i in b]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        result=[]\n",
    "        i=0\n",
    "        j=0\n",
    "        while i <len(nums1) and j<len(nums2):\n",
    "            if nums1[i][0]<nums2[j][0]:\n",
    "                result.append(nums1[i])\n",
    "                i=i+1\n",
    "                continue\n",
    "            elif nums1[i][0]==nums2[j][0]:\n",
    "                result.append([nums1[i][0],(nums1[i][1]+nums2[j][1])])\n",
    "                i=i+1\n",
    "                j=j+1\n",
    "                continue\n",
    "            if nums1[i][0]>nums2[j][0]:\n",
    "                result.append(nums2[j])\n",
    "                j=j+1\n",
    "        if i<len(nums1):\n",
    "            for e in nums1[i::]:\n",
    "                result.append(e)\n",
    "        elif j<len(nums2):\n",
    "            for e in nums2[j::]:\n",
    "                result.append(e)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        i, j = 0, 0\n",
    "        ans = []\n",
    "        n1, n2 = len(nums1), len(nums2)\n",
    "        while i < n1 and j < n2:\n",
    "            num1, num2 = nums1[i][0], nums2[j][0]\n",
    "            if num1 == num2:\n",
    "                ans.append([num1, nums1[i][1]+nums2[j][1]])\n",
    "                i += 1\n",
    "                j += 1\n",
    "            elif num1 > num2:\n",
    "                ans.append([num2, nums2[j][1]])\n",
    "                j += 1\n",
    "            else:\n",
    "                ans.append([num1, nums1[i][1]])\n",
    "                i += 1\n",
    "        while i < n1:\n",
    "            ans.append([nums1[i][0], nums1[i][1]])\n",
    "            i += 1\n",
    "        while j < n2:\n",
    "            ans.append([nums2[j][0], nums2[j][1]])\n",
    "            j += 1\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        index_1 = 0\n",
    "        index_2 = 0\n",
    "        output = []\n",
    "\n",
    "        while index_1 < len(nums1) and index_2 < len(nums2):\n",
    "            # get id and value\n",
    "            id1, val1 = nums1[index_1]\n",
    "            id2, val2 = nums2[index_2]\n",
    "            if id1 < id2:\n",
    "                output.append([id1, val1])\n",
    "                index_1 +=1\n",
    "            elif id1 > id2:\n",
    "                output.append([id2, val2])\n",
    "                index_2 +=1\n",
    "            else:\n",
    "                val_sum = val1+val2\n",
    "                output.append([id1, val_sum])\n",
    "                index_1 += 1\n",
    "                index_2 +=1\n",
    "\n",
    "        if index_1 == len(nums1):\n",
    "            output.extend(nums2[index_2::])\n",
    "        elif index_2 == len(nums2):\n",
    "            output.extend(nums1[index_1::])\n",
    "        \n",
    "        return output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        c = Counter()\n",
    "        for x, y in nums1:\n",
    "            c[x] += y\n",
    "        for x, y in nums2:\n",
    "            c[x] += y\n",
    "        return list(sorted(c.items()))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import Counter\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "          return list(sorted((Counter(dict(nums1)) + Counter(dict(nums2))).items(), key=lambda m: m[0]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        sz1, sz2 = len(nums1), len(nums2)\n",
    "        i, j = 0, 0\n",
    "        res = []\n",
    "        while i < sz1 and j < sz2:\n",
    "            if nums1[i][0] < nums2[j][0]:\n",
    "                res.append(nums1[i])\n",
    "                i += 1\n",
    "            elif nums1[i][0] == nums2[j][0]:\n",
    "                nums1[i][1] += nums2[j][1]\n",
    "                res.append(nums1[i])\n",
    "                i += 1\n",
    "                j += 1\n",
    "            else:\n",
    "                res.append(nums2[j])\n",
    "                j += 1\n",
    "        \n",
    "        if i < sz1:\n",
    "            res.extend(nums1[i:])\n",
    "        if j < sz2:\n",
    "            res.extend(nums2[j:])\n",
    "        \n",
    "        return res\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\r\n",
    "        temp = dict()\r\n",
    "        for i in nums1:\r\n",
    "            temp[i[0]] = i[1]\r\n",
    "        for j in nums2:\r\n",
    "            if j[0] in temp.keys():\r\n",
    "                temp[j[0]] += j[1]\r\n",
    "            else:\r\n",
    "                temp[j[0]] = j[1]\r\n",
    "        ans = list()\r\n",
    "        for a in sorted(temp.keys()):\r\n",
    "            ans.append([a,temp[a]])\r\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        c=Counter()\n",
    "        for i,num in nums1:\n",
    "            c[i]+=num\n",
    "        for i,num in nums2:\n",
    "            c[i]+=num\n",
    "        return sorted(c.items())\n",
    "\n",
    "        \n",
    "\n",
    "            \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        nums1.extend(nums2)\n",
    "        hash_d = {}\n",
    "        for i in nums1:\n",
    "            hash_d[i[0]] = hash_d.get(i[0],0) + i[1]\n",
    "        num = [[k,v] for k, v in hash_d.items()]\n",
    "        return sorted(num,key = lambda x:x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        ans, m, n = [], len(nums1), len(nums2)\n",
    "        cnt = defaultdict(int)\n",
    "        for x, y in nums1:\n",
    "            cnt[x] += y\n",
    "        for x, y in nums2:\n",
    "            cnt[x] += y\n",
    "        return sorted(list(cnt.items()))\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        dictsum = {}\n",
    "        for x,y in nums1:\n",
    "            dictsum[x] = y\n",
    "        for x,y in nums2:\n",
    "            if x in dictsum:\n",
    "                dictsum[x] += y\n",
    "            else:\n",
    "                dictsum[x] = y\n",
    "        return [[x,y] for x,y in sorted(dictsum.items(), key=lambda item: item[0])]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        i, j = 0, 0\n",
    "        ans = []\n",
    "        while i < len(nums1) and j < len(nums2):\n",
    "            if nums1[i][0] == nums2[j][0]:\n",
    "                ans += [[nums1[i][0], nums1[i][1] + nums2[j][1]]]\n",
    "                i += 1\n",
    "                j += 1\n",
    "            elif nums1[i][0] < nums2[j][0]:\n",
    "                ans += [nums1[i]]\n",
    "                i += 1\n",
    "            else:\n",
    "                ans += [nums2[j]]\n",
    "                j += 1\n",
    "        if i < len(nums1):\n",
    "            ans += nums1[i:]\n",
    "        elif j < len(nums2):\n",
    "            ans += nums2[j:]\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        d = defaultdict(int)\n",
    "        for k, v in nums1:\n",
    "            d[k] += v\n",
    "        for k, v in nums2:\n",
    "            d[k] += v\n",
    "        ans = [[k, v] for k, v in d.items()]\n",
    "        ans.sort()\n",
    "        return ans\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        nums1.extend(nums2)\n",
    "        hash_s = set()\n",
    "        hash_d = {}\n",
    "        for i in nums1:\n",
    "            hash_d[i[0]] = hash_d.get(i[0],0) + i[1]\n",
    "        num = [[k,v] for k, v in hash_d.items()]\n",
    "        return sorted(num,key = lambda x:x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from typing import List\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        # 创建一个字典来累加每个id的值\n",
    "        value_map = {}\n",
    "\n",
    "        # 遍历nums1和nums2并累加每个id的值\n",
    "        for id_val in nums1:\n",
    "            value_map[id_val[0]] = id_val[1]\n",
    "\n",
    "        for id_val in nums2:\n",
    "            # 如果id在字典中，累加值，否则将该id和值添加到字典中\n",
    "            if id_val[0] in value_map:\n",
    "                value_map[id_val[0]] += id_val[1]\n",
    "            else:\n",
    "                value_map[id_val[0]] = id_val[1]\n",
    "\n",
    "        # 从字典中提取排序后的结果\n",
    "        res = sorted([[k, v] for k, v in value_map.items()], key=lambda x: x[0])\n",
    "\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        \"\"\"\n",
    "        res = []\n",
    "        n = max(nums1[-1][1], nums2[-1][1]\n",
    "        for i in range(n):\n",
    "            if nums1[i][0] - i != 1:\n",
    "                nums1.extend([i+1,0])\n",
    "                continue\n",
    "        for i in range(n):\n",
    "            if nums2[i][0] - i != 1:\n",
    "                nums2.extend([i+1,0])\n",
    "                continue\n",
    "        for i in range(n):\n",
    "            res.extend([i+1, nums1[i][1]+nums2[i][1]])\n",
    "        return res\n",
    "        \"\"\"\n",
    "        hp = {}\n",
    "        for id, value in nums1:\n",
    "            if id not in hp.keys():\n",
    "                hp[id] = value\n",
    "            else:\n",
    "                hp[id] += value\n",
    "        for id2, value2 in nums2:\n",
    "            if id2 not in hp.keys():\n",
    "                hp[id2] = value2\n",
    "            else:\n",
    "                hp[id2] += value2\n",
    "        res = sorted(hp.items(), key=lambda d: d[0], reverse=False)\n",
    "        return res\n",
    "        \n",
    "\n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        dic=[0]*1001\n",
    "        for i in nums1:\n",
    "            dic[i[0]]=dic[i[0]]+i[1]\n",
    "        for i in nums2:\n",
    "            dic[i[0]]=dic[i[0]]+i[1]\n",
    "        ans=[]\n",
    "        for i,x in enumerate(dic):\n",
    "            if x!=0:\n",
    "                ans.append([i,x])\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        m = Counter() #字典解析 利用字典唯一key的特性保存数组的起始索引 相同的则增加 不同的则加入这个key\n",
    "        for x,y in nums1+nums2: m[x]+=y\n",
    "        # 对字典的key进行排序\n",
    "        return sorted(m.items())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        d = {}\n",
    "        chu = []\n",
    "        for i in nums1:\n",
    "            d[i[0]] = i[1]\n",
    "        for i in nums2:\n",
    "            try:\n",
    "                d[i[0]] += i[1]\n",
    "            except:\n",
    "                d[i[0]] = i[1]\n",
    "        for a,b in d.items():\n",
    "            chu.append([a,b])\n",
    "        chu.sort(key = lambda x:x[0])\n",
    "        return chu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        fh = []\n",
    "        x = y = 0\n",
    "        a, b = len(nums1), len(nums2)\n",
    "        while x < a and y < b:\n",
    "            if nums1[x][0] < nums2[y][0]:\n",
    "                fh.append(nums1[x])\n",
    "                x += 1\n",
    "            elif nums1[x][0] == nums2[y][0]:\n",
    "                fh.append([nums1[x][0], nums1[x][1]+nums2[y][1]])\n",
    "                x += 1\n",
    "                y += 1\n",
    "            else:\n",
    "                fh.append(nums2[y])\n",
    "                y += 1\n",
    "        return fh + nums1[x:] + nums2[y:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        nums1.extend(nums2)\n",
    "        hash_d = {}\n",
    "        for i in nums1:\n",
    "            hash_d[i[0]] = hash_d.get(i[0],0) + i[1]\n",
    "        num = [[k,v] for k, v in hash_d.items()]\n",
    "        return sorted(num,key = lambda x:x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, num1s, num2s):\n",
    "        num1l, num2l = len(num1s), len(num2s)\n",
    "        i, j = 0, 0\n",
    "        result = []\n",
    "        while i < num1l and j < num2l:\n",
    "            if num1s[i][0] < num2s[j][0]:\n",
    "                result.append(num1s[i])\n",
    "                i += 1\n",
    "            elif num1s[i][0] > num2s[j][0]:\n",
    "                result.append(num2s[j])\n",
    "                j += 1\n",
    "            else:\n",
    "                result.append([num1s[i][0], num1s[i][1] + num2s[j][1]])\n",
    "                i += 1\n",
    "                j += 1\n",
    "        if i < num1l:\n",
    "            result.extend(num1s[i:])\n",
    "        elif j < num2l:\n",
    "            result.extend(num2s[j:])\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        nums1.append([2000, 0])\n",
    "        nums2.append([2001, 0])\n",
    "        it1, it2 = iter(nums1), iter(nums2)\n",
    "        id2, n2 = next(it2)\n",
    "        res = []\n",
    "        for id1, n1 in nums1:\n",
    "            while id2 < id1:\n",
    "                res.append([id2, n2])\n",
    "                id2, n2 = next(it2)\n",
    "            res.append([id1, n1]) \n",
    "            if id1 == id2:\n",
    "                res[-1][1] += n2\n",
    "                id2, n2 = next(it2)\n",
    "        res.pop()\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        res,m,n=[],len(nums1),len(nums2)\n",
    "        i,j=0,0\n",
    "        while i<m and j<n:\n",
    "            if nums1[i][0]==nums2[j][0]:\n",
    "                t=nums1[i][1]+nums2[j][1]\n",
    "                res.append([nums1[i][0],t])\n",
    "                i+=1\n",
    "                j+=1\n",
    "            elif nums1[i][0]>nums2[j][0]:\n",
    "                res.append(nums2[j])\n",
    "                j+=1\n",
    "            elif nums1[i][0]<nums2[j][0]:\n",
    "                res.append(nums1[i])\n",
    "                i+=1\n",
    "\n",
    "        if i<m:\n",
    "            res.extend(nums1[i:])\n",
    "        if j<n:\n",
    "            res.extend(nums2[j:])\n",
    "\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        d = Counter()\n",
    "        for x, y in nums1: d[x] += y\n",
    "        for x, y in nums2: d[x] += y\n",
    "        return list(sorted(d.items()))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "\n",
    "        res = []\n",
    "\n",
    "        while nums1 and nums2:\n",
    "            if nums1[0][0] == nums2[0][0]:\n",
    "                res.append([nums1[0][0], nums1[0][1] + nums2[0][1]])\n",
    "                nums1.pop(0)\n",
    "                nums2.pop(0)\n",
    "            elif nums1[0][0] > nums2[0][0]:\n",
    "                res.append(nums2.pop(0))\n",
    "            else:\n",
    "                res.append(nums1.pop(0))\n",
    "        \n",
    "        if nums1:\n",
    "            res.extend(nums1)\n",
    "        if nums2:\n",
    "            res.extend(nums2)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        len1=len(nums1)\n",
    "        len2=len(nums2)\n",
    "        ans=[]\n",
    "        l=r=0\n",
    "        while True:\n",
    "            if l==len1:\n",
    "                ans+=nums2[r:]\n",
    "                return ans\n",
    "            if r==len2:\n",
    "                ans+=nums1[l:]\n",
    "                return ans\n",
    "            if nums1[l][0]==nums2[r][0]:\n",
    "                nums1[l][1]+=nums2[r][1]\n",
    "                ans.append(nums1[l])\n",
    "                l+=1\n",
    "                r+=1\n",
    "            elif nums1[l][0]>nums2[r][0]:\n",
    "                ans.append(nums2[r])\n",
    "                r+=1\n",
    "            else:\n",
    "                ans.append(nums1[l])\n",
    "                l+=1\n",
    "        return ans\n",
    "\n",
    "            \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        dic = Counter()\n",
    "        for k, v in nums1 + nums2:\n",
    "            dic[k] += v\n",
    "        return sorted([[k, v] for k, v in dic.items()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        l1 = len(nums1)\n",
    "        l2 = len(nums2)\n",
    "        p1 = p2 = 0\n",
    "        while p1<l1 and p2 < l2:\n",
    "            if nums1[p1][0] == nums2[p2][0]:\n",
    "                nums1[p1][1] += nums2[p2][1]\n",
    "                p1 += 1\n",
    "                p2 += 1\n",
    "            elif nums1[p1][0] < nums2[p2][0]:\n",
    "                p1+=1\n",
    "            else:\n",
    "                nums1.append(nums2[p2])\n",
    "                p2 +=1\n",
    "\n",
    "        if p2 != l2:\n",
    "            nums1 += nums2[p2:]\n",
    "        \n",
    "        return sorted(nums1,key = lambda x:x[0])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        dic = defaultdict(int)\n",
    "        for num in nums1:\n",
    "            dic[num[0]] += num[1]\n",
    "        for num in nums2:\n",
    "            dic[num[0]] += num[1]\n",
    "        \n",
    "        return sorted([[k, v] for k, v in dic.items()], key=lambda x: x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "\n",
    "        i =j = 0\n",
    "        ans=[]\n",
    "        n,m = len(nums1),len(nums2)\n",
    "        while i < n and j < m:\n",
    "            if nums1[i][0] < nums2[j][0]:\n",
    "                ans.append(nums1[i])\n",
    "                i+=1\n",
    "            elif nums1[i][0] > nums2[j][0]:\n",
    "                ans.append(nums2[j])\n",
    "                j+=1\n",
    "            else :\n",
    "                ans.append([nums1[i][0],nums1[i][1]+nums2[j][1]])\n",
    "                i+=1\n",
    "                j+=1\n",
    "        while j<m :\n",
    "            ans.append(nums2[j])\n",
    "            j+=1\n",
    "\n",
    "        while i<n:\n",
    "            ans.append(nums1[i])\n",
    "            i+=1\n",
    "\n",
    "        return ans "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        dic = defaultdict(int)\n",
    "        for num in nums1:\n",
    "            dic[num[0]] += num[1]\n",
    "        for num in nums2:\n",
    "            dic[num[0]] += num[1]\n",
    "        \n",
    "        res = []\n",
    "        for item in dic.items():\n",
    "            res.append([item[0], item[1]])\n",
    "\n",
    "        return sorted(res, key=lambda x: x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        left1 = left2 = 0\n",
    "        n1 = len(nums1)\n",
    "        n2 = len(nums2)\n",
    "        ans =[]\n",
    "        while left1 < n1 and left2 < n2:\n",
    "            if nums1[left1][0] == nums2[left2][0]:\n",
    "                ans.append([nums1[left1][0], nums1[left1][1] + nums2[left2][1]])\n",
    "                left1 += 1\n",
    "                left2 += 1\n",
    "            elif nums1[left1][0] < nums2[left2][0]:\n",
    "                ans.append([nums1[left1][0], nums1[left1][1]])\n",
    "                left1 += 1\n",
    "            else:\n",
    "                ans.append([nums2[left2][0], nums2[left2][1]])\n",
    "                left2 += 1\n",
    "        while left1 < n1:\n",
    "            ans.append([nums1[left1][0], nums1[left1][1]])\n",
    "            left1 += 1\n",
    "        while left2 < n2:\n",
    "            ans.append([nums2[left2][0], nums2[left2][1]])\n",
    "            left2 += 1\n",
    "\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        left1 = left2 = 0\n",
    "        n1 = len(nums1)\n",
    "        n2 = len(nums2)\n",
    "        ans =[]\n",
    "        while left1 < n1 and left2 < n2:\n",
    "            if nums1[left1][0] == nums2[left2][0]:\n",
    "                ans.append([nums1[left1][0], nums1[left1][1] + nums2[left2][1]])\n",
    "                left1 += 1\n",
    "                left2 += 1\n",
    "            elif nums1[left1][0] < nums2[left2][0]:\n",
    "                ans.append([nums1[left1][0], nums1[left1][1]])\n",
    "                left1 += 1\n",
    "            else:\n",
    "                ans.append([nums2[left2][0], nums2[left2][1]])\n",
    "                left2 += 1\n",
    "        while left1 < n1:\n",
    "            ans.append([nums1[left1][0], nums1[left1][1]])\n",
    "            left1 += 1\n",
    "        while left2 < n2:\n",
    "            ans.append([nums2[left2][0], nums2[left2][1]])\n",
    "            left2 += 1\n",
    "\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        dic = defaultdict(int)\n",
    "        for num in nums1:\n",
    "            dic[num[0]] += num[1]\n",
    "        for num in nums2:\n",
    "            dic[num[0]] += num[1]\n",
    "        \n",
    "        return sorted([[k, v] for k, v in dic.items()], key=lambda x: x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        combined = nums1 + nums2\n",
    "        id_sums = {}\n",
    "        for id,val in combined:\n",
    "            if id in id_sums:\n",
    "                id_sums[id]+=val\n",
    "            else:\n",
    "                id_sums[id]=val\n",
    "            result=[[id,val] for id,val in sorted(id_sums.items())]\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        i, j = 0, 0\n",
    "        ans = []\n",
    "        n1, n2 = len(nums1), len(nums2)\n",
    "        while i < n1 and j < n2:\n",
    "            num1, num2 = nums1[i][0], nums2[j][0]\n",
    "            if num1 == num2:\n",
    "                ans.append([num1, nums1[i][1]+nums2[j][1]])\n",
    "                i += 1\n",
    "                j += 1\n",
    "            elif num1 > num2:\n",
    "                ans.append([num2, nums2[j][1]])\n",
    "                j += 1\n",
    "            else:\n",
    "                ans.append([num1, nums1[i][1]])\n",
    "                i += 1\n",
    "        while i < n1:\n",
    "            ans.append([nums1[i][0], nums1[i][1]])\n",
    "            i += 1\n",
    "        while j < n2:\n",
    "            ans.append([nums2[j][0], nums2[j][1]])\n",
    "            j += 1\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n",
    "        return list(sorted((Counter(dict(A)) + Counter(dict(B))).items()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        d = collections.defaultdict(int)\n",
    "        for i, v in nums1:\n",
    "            d[i] += v\n",
    "        \n",
    "        for i, v in nums2:\n",
    "            d[i] += v\n",
    "        \n",
    "        ret = []\n",
    "        for i, v in d.items():\n",
    "            ret.append((i, v))\n",
    "\n",
    "        ret.sort()\n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        a=[]\n",
    "        for i in nums1:\n",
    "            if i[0]  not in a:\n",
    "                a.append(i[0])\n",
    "        for i in nums2:\n",
    "            if i [0] not in a:\n",
    "                a.append(i[0])\n",
    "        maxnum=max(a)\n",
    "        nums=[]\n",
    "        dic={}\n",
    "        a.sort()\n",
    "        for i in range(0,len(a)):\n",
    "            dic[a[i]]=0\n",
    "        nums3=nums1+nums2\n",
    "        for i in range(0,len(nums3)):\n",
    "            dic[nums3[i][0]]+=nums3[i][1]\n",
    "        for i in dic.keys():\n",
    "            nums.append([i,dic[i]])\n",
    "        return nums\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        nums1.extend(nums2)\n",
    "        hash_d = {}\n",
    "        for i in nums1:\n",
    "            hash_d[i[0]] = hash_d.get(i[0],0) + i[1]\n",
    "        num = [[k,v] for k, v in hash_d.items()]\n",
    "        return sorted(num,key = lambda x:x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        dictsum = {}\n",
    "        for x,y in nums1:\n",
    "            dictsum[x] = y\n",
    "        for x,y in nums2:\n",
    "            if x in dictsum:\n",
    "                dictsum[x] += y\n",
    "            else:\n",
    "                dictsum[x] = y\n",
    "        a = sorted(dictsum.items(), key=lambda item: item[0])\n",
    "        return [[x,y] for x,y in a]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        m = Counter() \n",
    "        for x,y in nums1:\n",
    "            m[x]+=y\n",
    "        for x,y in nums2:\n",
    "            m[x]+=y\n",
    "        return sorted(m.items())\n",
    "\n",
    "            \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        ans=[]\n",
    "        m,n=len(nums1),len(nums2)\n",
    "        i,j=0,0\n",
    "        while i<m and j<n:\n",
    "            if nums1[i][0] == nums2[j][0]:\n",
    "                ans.append([nums1[i][0],nums1[i][1]+nums2[j][1]])\n",
    "                i+=1\n",
    "                j+=1\n",
    "            elif nums1[i][0] < nums2[j][0]:\n",
    "                ans.append(nums1[i])\n",
    "                i+=1\n",
    "            elif nums1[i][0] > nums2[j][0]:\n",
    "                ans.append(nums2[j])\n",
    "                j+=1\n",
    "        if i<m:\n",
    "            ans.extend(nums1[i:])\n",
    "        if j<n:\n",
    "            ans.extend(nums2[j:])\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        cal = [0] * 1005\n",
    "        for l in nums1:\n",
    "            k = l[0]\n",
    "            v = l[1]\n",
    "            cal[k] += v\n",
    "        for l in nums2:\n",
    "            k = l[0]\n",
    "            v = l[1]\n",
    "            cal[k] += v\n",
    "        ans = []\n",
    "        for i, v in enumerate(cal):\n",
    "            if v != 0:\n",
    "                ans.append([i, v])\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        dict = {}\n",
    "        res = []\n",
    "        for id, val in nums1:\n",
    "            dict[id] = val\n",
    "        for id, val in nums2:\n",
    "            if id not in dict:\n",
    "                dict[id] = val\n",
    "            else:\n",
    "                dict[id] += val\n",
    "        for k, v in dict.items():\n",
    "            res.append([k, v])\n",
    "        return sorted(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        d = collections.Counter()\n",
    "        for x,y in nums1:d[x] += y\n",
    "        for x,y in nums2:d[x] += y\n",
    "        return list(sorted(d.items()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        m = len(nums1)\n",
    "        n = len(nums2)\n",
    "        i,j =0,0\n",
    "        ans = []\n",
    "        while i<m or j<n:\n",
    "            if i<m and j<n:\n",
    "                if nums1[i][0]==nums2[j][0]:\n",
    "                    ans.append([nums1[i][0],nums1[i][1]+nums2[j][1]])\n",
    "                    i+=1\n",
    "                    j+=1\n",
    "                elif nums1[i][0]<nums2[j][0]:\n",
    "                    ans.append(nums1[i][:])\n",
    "                    i+=1\n",
    "                else:\n",
    "                    ans.append(nums2[j][:])\n",
    "                    j+=1\n",
    "            else:\n",
    "                if i<m:\n",
    "                    ans.extend(nums1[i:])\n",
    "                    break\n",
    "                else:\n",
    "                    ans.extend(nums2[j:])\n",
    "                    break\n",
    "        \n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        d = collections.defaultdict(int)\n",
    "        for x, y in nums1:\n",
    "            d[x] += y\n",
    "        for x, y in nums2:\n",
    "            d[x] += y\n",
    "        # print(d)\n",
    "        res = list(d.items())\n",
    "        res.sort()\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        i = j = 0\n",
    "        m, n = len(nums1), len(nums2)\n",
    "        ans = []\n",
    "        while i < m or j < n:\n",
    "            if i == m:\n",
    "                ans += nums2[j:]\n",
    "                break\n",
    "            if j == n:\n",
    "                ans += nums1[i:]\n",
    "                break\n",
    "            if nums1[i][0] == nums2[j][0]:\n",
    "                ans.append([nums1[i][0], nums1[i][1] + nums2[j][1]])\n",
    "                i += 1\n",
    "                j += 1\n",
    "            elif nums1[i][0] > nums2[j][0]:\n",
    "                ans.append(nums2[j])\n",
    "                j += 1\n",
    "            elif nums1[i][0] < nums2[j][0]:\n",
    "                ans.append(nums1[i])\n",
    "                i += 1\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        HashMap = defaultdict()\n",
    "        for num in nums1:\n",
    "            if num[0] not in HashMap:\n",
    "                HashMap[num[0]] = num[1]\n",
    "            else:\n",
    "                HashMap[num[0]] += num[1]\n",
    "        for num in nums2:\n",
    "            if num[0] not in HashMap:\n",
    "                HashMap[num[0]] = num[1]\n",
    "            else:\n",
    "                HashMap[num[0]] += num[1]\n",
    "        ans = []\n",
    "        for key, value in HashMap.items():\n",
    "            ans.append([key, value])\n",
    "        ans.sort(key = lambda x: x[0])\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        ans = []\n",
    "        i = j = 0\n",
    "        m, n = len(nums1), len(nums2)\n",
    "        while i < m and j < n:\n",
    "            while i < m and nums1[i][0] < nums2[j][0]:\n",
    "                ans.append(nums1[i])\n",
    "                i += 1\n",
    "            while i < m and j < n and nums2[j][0] < nums1[i][0]:\n",
    "                ans.append(nums2[j])\n",
    "                j += 1\n",
    "            if i < m and j < n and nums1[i][0] == nums2[j][0]:\n",
    "                ans.append([nums1[i][0], nums1[i][1] + nums2[j][1]])\n",
    "                i += 1\n",
    "                j += 1\n",
    "        return ans + nums1[i:] + nums2[j:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        i,j = 0,0\n",
    "        res = []\n",
    "        while i < len(nums1) and j < len(nums2):\n",
    "            if nums1[i][0] == nums2[j][0]:\n",
    "                res.append([nums1[i][0],nums1[i][1]+nums2[j][1]])\n",
    "                i += 1\n",
    "                j += 1\n",
    "            elif nums1[i][0] < nums2[j][0]:\n",
    "                res.append(nums1[i])\n",
    "                i += 1\n",
    "            else:\n",
    "                res.append(nums2[j])\n",
    "                j += 1\n",
    "        for k in range(i,len(nums1)):\n",
    "            res.append(nums1[k])\n",
    "        for k in range(j,len(nums2)):\n",
    "            res.append(nums2[k])\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n",
    "        return list(sorted((Counter(dict(nums1)) + Counter(dict(nums2))).items()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        if t1 is None:\n",
    "            if t2 is None:\n",
    "                return None\n",
    "            else:\n",
    "                return t2\n",
    "        else:\n",
    "            if t2 is None:\n",
    "                return t1\n",
    "            \n",
    "        return TreeNode(t1.val + t2.val, self.mergeTrees(t1.left, t2.left), self.mergeTrees(t1.right, t2.right))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1, t2):\n",
    "        \"\"\"\n",
    "        :type t1: TreeNode\n",
    "        :type t2: TreeNode\n",
    "        :rtype: TreeNode\n",
    "        \"\"\"\n",
    "        if not t1:\n",
    "            return t2\n",
    "        if not t2:\n",
    "            return t1\n",
    "        head = t1\n",
    "        queue1 = [t1]\n",
    "        queue2 = [t2]\n",
    "        while queue1:\n",
    "            node1 = queue1.pop(0)\n",
    "            node2 = queue2.pop(0)\n",
    "            node1.val += node2.val\n",
    "            if node1.left and node2.left:\n",
    "                queue1.append(node1.left)\n",
    "                queue2.append(node2.left)\n",
    "            elif node2.left:\n",
    "                node1.left = node2.left\n",
    "            if node1.right and node2.right:\n",
    "                queue1.append(node1.right)\n",
    "                queue2.append(node2.right)\n",
    "            elif node2.right:\n",
    "                node1.right = node2.right\n",
    "        return head\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1, t2):\n",
    "        \"\"\"\n",
    "        :type t1: TreeNode\n",
    "        :type t2: TreeNode\n",
    "        :rtype: TreeNode\n",
    "        \"\"\"\n",
    "        # if t1 and t2:\n",
    "        #     t = TreeNode(t1.val + t2.val)\n",
    "        #     t.left = self.mergeTrees(t1.left, t2.left)\n",
    "        #     t.right = self.mergeTrees(t1.right, t2.right)\n",
    "        # else:\n",
    "        #     t = t1 if t1 else t2\n",
    "        # return t\n",
    "        \n",
    "        \"\"\"\n",
    "        非递归实现\n",
    "        https://leetcode.com/problems/merge-two-binary-trees/discuss/104429/Python-BFS-Solution\n",
    "        主要思路：\n",
    "        对于两棵树的同一位置的某个节点，\n",
    "        1：都有左右孩子节点      节点值直接相加\n",
    "        2: 都没有左右孩子节点    直接返回，检查下一个节点\n",
    "        3/4：一左一右，一右一左  对于不存在的孩子节点，新增一个val=0的节点，转换成情况1再相加\n",
    "        \"\"\"\n",
    "\n",
    "        if not (t1 and t2):\n",
    "            return t1 or t2\n",
    "        queue1, queue2 = collections.deque([t1]), collections.deque([t2])\n",
    "        while queue1 and queue2:\n",
    "            node1, node2 = queue1.popleft(), queue2.popleft()\n",
    "            if node1 and node2:\n",
    "                node1.val = node1.val + node2.val\n",
    "                if (not node1.left) and node2.left:\n",
    "                    node1.left = TreeNode(0)\n",
    "                if (not node1.right) and node2.right:\n",
    "                    node1.right = TreeNode(0)\n",
    "                queue1.append(node1.left)\n",
    "                queue1.append(node1.right)\n",
    "                queue2.append(node2.left)\n",
    "                queue2.append(node2.right)\n",
    "        return t1\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1, t2):\n",
    "        \"\"\"\n",
    "        :type t1: TreeNode\n",
    "        :type t2: TreeNode\n",
    "        :rtype: TreeNode\n",
    "        \"\"\"\n",
    "        if t1 is None and t2 is None:\n",
    "            return None\n",
    "        elif t1 is None and t2 is not None:\n",
    "            return t2\n",
    "        elif t1 is not None and t2 is None:\n",
    "            return t1\n",
    "        else:\n",
    "            t1.val = t2.val + t1.val\n",
    "            t1.left = self.mergeTrees(t1.left, t2.left)\n",
    "            t1.right = self.mergeTrees(t1.right, t2.right)\n",
    "            return t1\n",
    "            \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1, t2):\n",
    "        \"\"\"\n",
    "        :type t1: TreeNode\n",
    "        :type t2: TreeNode\n",
    "        :rtype: TreeNode\n",
    "        \"\"\"\n",
    "        if (t2 is None): return t1\n",
    "        if (t1 is None): return t2\n",
    "        merged = TreeNode(t1.val + t2.val)\n",
    "        merged.left = self.mergeTrees(t1.left, t2.left)\n",
    "        merged.right = self.mergeTrees(t1.right, t2.right)\n",
    "        return merged\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1, t2):\n",
    "        \"\"\"\n",
    "        :type t1: TreeNode\n",
    "        :type t2: TreeNode\n",
    "        :rtype: TreeNode\n",
    "        \"\"\"\n",
    "        if t1 and t2:\n",
    "            t1.val += t2.val\n",
    "            t1.left = self.mergeTrees(t1.left,t2.left)\n",
    "            t1.right = self.mergeTrees(t1.right,t2.right)\n",
    "            return t1\n",
    "        if t2:\n",
    "            return t2\n",
    "        if t1:\n",
    "            return t1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1, t2):\n",
    "        \n",
    "        \n",
    "        if  t1 or t2:\n",
    "            v1,v2=0,0\n",
    "            t1l,t2l,t1r,t2r=None,None,None,None\n",
    "            if t1 :\n",
    "                v1=t1.val \n",
    "                t1l=t1.left\n",
    "                t1r=t1.right\n",
    "            if t2 :\n",
    "                v2=t2.val \n",
    "                v2=t2.val \n",
    "                t2l=t2.left\n",
    "                t2r=t2.right\n",
    "            tn=TreeNode(v1+v2)\n",
    "            tn.left=self.mergeTrees(t1l, t2l)\n",
    "            tn.right=self.mergeTrees(t1r, t2r)\n",
    "            return tn\n",
    "        else:\n",
    "            return None\n",
    "        \n",
    "                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode):\n",
    "        if t1 and not t2:\n",
    "                return t1\n",
    "        if not t1 and t2:\n",
    "                return t2\n",
    "        if t1 and t2:\n",
    "                root = TreeNode(t1.val + t2.val)\n",
    "                root.left = self.mergeTrees(t1.left,t2.left)\n",
    "                root.right = self.mergeTrees(t1.right, t2.right)\n",
    "                return root"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: 'TreeNode', t2: 'TreeNode') -> 'TreeNode':\n",
    "        merge_t1_t2 = TreeNode(None)\n",
    "        if t1 and t2:\n",
    "            merge_t1_t2.val = t1.val+t2.val\n",
    "            merge_t1_t2.left = self.mergeTrees(t1.left, t2.left)\n",
    "            merge_t1_t2.right = self.mergeTrees(t1.right, t2.right) \n",
    "            return merge_t1_t2\n",
    "        elif t1:\n",
    "            merge_t1_t2.val = t1.val\n",
    "            merge_t1_t2.left = self.mergeTrees(t1.left, None)\n",
    "            merge_t1_t2.right = self.mergeTrees(t1.right, None) \n",
    "            return merge_t1_t2\n",
    "        elif t2:\n",
    "            merge_t1_t2.val = t2.val\n",
    "            merge_t1_t2.left = self.mergeTrees(None, t2.left)\n",
    "            merge_t1_t2.right = self.mergeTrees(None, t2.right) \n",
    "            return merge_t1_t2\n",
    "        else:\n",
    "            merge_t1_t2.val = None\n",
    "            \n",
    "        \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1, t2):\n",
    "        \"\"\"\n",
    "        :type t1: TreeNode\n",
    "        :type t2: TreeNode\n",
    "        :rtype: TreeNode\n",
    "        \"\"\"\n",
    "        if not t1 and not t2:\n",
    "            return []\n",
    "        def mt(node1, node2, t):\n",
    "            rev = 0\n",
    "            if not node1 and not node2:\n",
    "                return\n",
    "            if node1:\n",
    "                rev += node1.val\n",
    "            if node2:\n",
    "                rev += node2.val\n",
    "            t.val = rev\n",
    "            if node1 and node1.left or node2 and node2.left:\n",
    "                t.left = TreeNode(0)\n",
    "                mt(node1.left if node1 else None, node2.left if node2 else None, t.left)\n",
    "            if node1 and node1.right or node2 and node2.right:\n",
    "                t.right = TreeNode(0)\n",
    "                mt(node1.right if node1 else None, node2.right if node2 else None, t.right)\n",
    "            \n",
    "        t = TreeNode(0)        \n",
    "        x = t\n",
    "        mt(t1, t2, t)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1, t2):\n",
    "        \"\"\"\n",
    "        :type t1: TreeNode\n",
    "        :type t2: TreeNode\n",
    "        :rtype: TreeNode\n",
    "        \"\"\"\n",
    "        def mmerge(cur1, cur2):\n",
    "            if cur1 == None and cur2 == None: return None\n",
    "            curt = TreeNode(0)\n",
    "            if cur1 != None: curt.val += cur1.val\n",
    "            if cur2 != None: curt.val += cur2.val\n",
    "            curt.left = mmerge(cur1.left if cur1 != None else None, cur2.left if cur2 != None else None)\n",
    "            curt.right = mmerge(cur1.right if cur1 != None else None, cur2.right if cur2 != None else None)\n",
    "            return curt\n",
    "                \n",
    "        return mmerge(t1, t2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        if t1 is None:\n",
    "            return t2\n",
    "        if t2 is None:\n",
    "            return t1\n",
    "        stack1 = [t1]\n",
    "        stack2 = [t2]\n",
    "        i = 0\n",
    "        while i < len(stack1):\n",
    "            if stack1[i] and stack2[i]:\n",
    "                stack1[i].val += stack2[i].val\n",
    "            if stack1[i].left and stack2[i].left:\n",
    "                stack1.append(stack1[i].left)\n",
    "                stack2.append(stack2[i].left)\n",
    "            elif not stack1[i].left:\n",
    "                stack1[i].left = stack2[i].left\n",
    "\n",
    "            if stack1[i].right and stack2[i].right:\n",
    "                stack1.append(stack1[i].right)\n",
    "                stack2.append(stack2[i].right)\n",
    "            elif not stack1[i].right:\n",
    "                stack1[i].right = stack2[i].right\n",
    "            \n",
    "            i+=1\n",
    "        return t1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        if t1 and t2:\n",
    "            t1.val += t2.val\n",
    "            t1.left = self.mergeTrees(t1.left, t2.left)\n",
    "            t1.right = self.mergeTrees(t1.right, t2.right)\n",
    "            return t1\n",
    "        return t1 or t2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        \n",
    "        def recursion_merge(t1,t2):\n",
    "            if t1 is None:\n",
    "                return t2\n",
    "            if t2 is None:\n",
    "                return t1\n",
    "            t1.val += t2.val\n",
    "            t1.left = merge(t1.left,t2.left)\n",
    "            t1.right = merge(t1.right,t2.right)\n",
    "            return t1\n",
    "\n",
    "        def iterative_merge(t1,t2):\n",
    "            if not t1:\n",
    "                return t2\n",
    "            if not t2:\n",
    "                return t1\n",
    "            stack = [(t1,t2)]\n",
    "            while len(stack) > 0:\n",
    "                t = stack.pop(0)\n",
    "                t[0].val += t[1].val\n",
    "                if t[0].left and t[1].left:\n",
    "                    stack.append((t[0].left,t[1].left))\n",
    "                elif (not t[0].left) and t[1].left:\n",
    "                    t[0].left = t[1].left\n",
    "                else:\n",
    "                    pass\n",
    "                if t[0].right and t[1].right:\n",
    "                    stack.append((t[0].right,t[1].right))\n",
    "                elif (not t[0].right) and t[1].right:\n",
    "                    t[0].right = t[1].right\n",
    "                else:\n",
    "                    pass\n",
    "            return t1\n",
    "\n",
    "        return iterative_merge(t1,t2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        \n",
    "        def recursion_merge(t1,t2):\n",
    "            if t1 is None:\n",
    "                return t2\n",
    "            if t2 is None:\n",
    "                return t1\n",
    "            t1.val += t2.val\n",
    "            t1.left = merge(t1.left,t2.left)\n",
    "            t1.right = merge(t1.right,t2.right)\n",
    "            return t1\n",
    "\n",
    "        def iterative_merge(t1,t2):\n",
    "            if not t1:\n",
    "                return t2\n",
    "            if not t2:\n",
    "                return t1\n",
    "            stack = [(t1,t2)]\n",
    "            while len(stack) > 0:\n",
    "                t = stack.pop(0)\n",
    "                t[0].val += t[1].val\n",
    "                if t[0].left and t[1].left:\n",
    "                    stack.append((t[0].left,t[1].left))\n",
    "                elif (not t[0].left) and t[1].left:\n",
    "                    t[0].left = t[1].left\n",
    "                else:\n",
    "                    pass\n",
    "                if t[0].right and t[1].right:\n",
    "                    stack.append((t[0].right,t[1].right))\n",
    "                elif (not t[0].right) and t[1].right:\n",
    "                    t[0].right = t[1].right\n",
    "                else:\n",
    "                    pass\n",
    "            return t1\n",
    "\n",
    "        return iterative_merge(t1,t2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        if t1==None and t2==None:\n",
    "            return None\n",
    "        if t1==None:\n",
    "            return t2\n",
    "        if t2==None:\n",
    "            return t1\n",
    "        arr_1=[t1]\n",
    "        arr_2=[t2]\n",
    "        while len(arr_1)>0 and len(arr_2)>0:\n",
    "            arr_1[0].val+=arr_2[0].val\n",
    "            if arr_1[0].left is not None and arr_2[0].left is not None:\n",
    "                arr_1.append(arr_1[0].left)\n",
    "                arr_2.append(arr_2[0].left)\n",
    "            if arr_1[0].right is not None and arr_2[0].right is not None:\n",
    "                arr_1.append(arr_1[0].right)\n",
    "                arr_2.append(arr_2[0].right)\n",
    "            if arr_1[0].left is None and arr_2[0].left is not None:\n",
    "                arr_1[0].left=arr_2[0].left\n",
    "            if arr_1[0].right is None and arr_2[0].right is not None:\n",
    "                arr_1[0].right=arr_2[0].right\n",
    "            arr_1.pop(0)\n",
    "            arr_2.pop(0)\n",
    "        return t1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        if not t1 or not t2:\n",
    "            return t2 if not t1 else t1\n",
    "        queue = [(t1,t2)]\n",
    "        while queue:\n",
    "            r1,r2 = queue.pop()\n",
    "            r1.val += r2.val\n",
    "            if r1.left and r2.left:\n",
    "                queue.append((r1.left,r2.left))\n",
    "            elif not r1.left:\n",
    "                r1.left = r2.left\n",
    "            if r1.right and r2.right:\n",
    "                queue.append((r1.right,r2.right))\n",
    "            elif not r1.right:\n",
    "                r1.right = r2.right\n",
    "        return t1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        if not (t1 and t2):\n",
    "            return t1 if t1 else t2\n",
    "        queue = [(t1, t2)]\n",
    "        while queue:\n",
    "            r1, r2 = queue.pop(0)\n",
    "            r1.val += r2.val\n",
    "            if r1.left and r2.left:\n",
    "                queue.append((r1.left, r2.left))\n",
    "            elif not r1.left:\n",
    "                r1.left = r2.left\n",
    "            \n",
    "            if r1.right and r2.right:\n",
    "                queue.append((r1.right, r2.right))\n",
    "            elif not r1.right:\n",
    "                r1.right = r2.right\n",
    "\n",
    "        return t1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        if not t1 and t2:\n",
    "            return t2\n",
    "        elif t1 and t2:\n",
    "            t1.val = t1.val+t2.val\n",
    "            t1.left = self.mergeTrees(t1.left,t2.left)\n",
    "            t1.right = self.mergeTrees(t1.right,t2.right)\n",
    "        return t1\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        if t1 is None or t2 is None:\n",
    "            return t1 or t2\n",
    "        t1.val += t2.val\n",
    "        t1.left = self.mergeTrees(t1.left, t2.left)\n",
    "        t1.right = self.mergeTrees(t1.right, t2.right)\n",
    "        return t1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        if t1 and t2:\n",
    "            t1.val+=t2.val\n",
    "            t1.left=self.mergeTrees(t1.left,t2.left)\n",
    "            t1.right=self.mergeTrees(t1.right,t2.right)\n",
    "            return t1\n",
    "        return t1 or t2\n",
    "\n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.left = None\n",
    "#         self.right = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n",
    "        def dfs(t1,t2):\n",
    "           if not (t1 and t2):\n",
    "             return t1 if t1 else t2\n",
    "           t1.val = t1.val + t2.val\n",
    "           t1.left = dfs(t1.left,t2.left)\n",
    "           t1.right = dfs(t1.right, t2.right)\n",
    "           return t1;\n",
    "        return dfs(t1,t2)\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "from collections import deque\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:\n",
    "        if not root1:\n",
    "            return root2\n",
    "        if not root2:\n",
    "            return root1\n",
    "        st = [] \n",
    "        st.append(root1)\n",
    "        st.append(root2)\n",
    "        while st != []:\n",
    "            node2 = st.pop()\n",
    "            node1 = st.pop()\n",
    "            if node1.left and node2.left: \n",
    "                st.append(node1.left)\n",
    "                st.append(node2.left)\n",
    "            if node1.right and node2.right: \n",
    "                st.append(node1.right)\n",
    "                st.append(node2.right)\n",
    "            node1.val += node2.val\n",
    "            if not node1.left and node2.left: \n",
    "                node1.left = node2.left\n",
    "            if not node1.right and node2.right: \n",
    "                node1.right = node2.right\n",
    "        return root1\n",
    "\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:\n",
    "        if not root1 and not root2:\n",
    "            return None\n",
    "        elif not root1:\n",
    "            return root2\n",
    "        elif not root2:\n",
    "            return root1\n",
    "\n",
    "        from collections import deque\n",
    "\n",
    "        que = deque([root1, root2])\n",
    "\n",
    "        while que:\n",
    "            temp1 = que.popleft()\n",
    "            temp2 = que.popleft()\n",
    "            temp1.val += temp2.val\n",
    "\n",
    "            if temp1.left and temp2.left:\n",
    "                que.extend([temp1.left, temp2.left])\n",
    "            if temp1.right and temp2.right:\n",
    "                que.extend([temp1.right, temp2.right])\n",
    "\n",
    "            if not temp1.left and temp2.left:\n",
    "                temp1.left = temp2.left\n",
    "            if not temp1.right and temp2.right:\n",
    "                temp1.right = temp2.right\n",
    "\n",
    "        return root1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n",
    "        if not root1: return root2\n",
    "        if not root2: return root1\n",
    "        from collections import deque\n",
    "        q = deque([root1])\n",
    "        q.append(root2)\n",
    "        while q:\n",
    "            node1 = q.popleft()\n",
    "            node2 = q.popleft()\n",
    "            \n",
    "            if node1.left and node2.left:\n",
    "                q.append(node1.left)\n",
    "                q.append(node2.left)\n",
    "            if node1.right and node2.right:\n",
    "                q.append(node1.right)\n",
    "                q.append(node2.right)\n",
    "\n",
    "            node1.val += node2.val\n",
    "\n",
    "            if not node1.left and node2.left:\n",
    "                node1.left = node2.left\n",
    "            if not node1.right and node2.right:\n",
    "                node1.right = node2.right\n",
    "        \n",
    "        return root1\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n",
    "\n",
    "        if not root1 and not root2: return None\n",
    "        else:\n",
    "            if not root1: return root2\n",
    "            if not root2: return root1\n",
    "\n",
    "        isLeaf = lambda node: not node.left and not node.right\n",
    "        \n",
    "        tree1Que = deque([root1])\n",
    "        tree2Que = deque([root2])\n",
    "        root1.val += root2.val\n",
    "        while tree1Que or tree2Que:\n",
    "            lengthOfLayer = len(tree1Que)\n",
    "            for _ in range(lengthOfLayer):\n",
    "                node1 = tree1Que.popleft()\n",
    "                node2 = tree2Que.popleft()\n",
    "\n",
    "                if isLeaf(node1) and isLeaf(node2):\n",
    "                    continue\n",
    "\n",
    "                if node1.left and node2.left:\n",
    "                    node1.left.val += node2.left.val if node2.left else 0\n",
    "                elif not node1.left and node2.left:\n",
    "                    node1.left = TreeNode(node2.left.val)\n",
    "                if node1.right and node2.right:\n",
    "                    node1.right.val += node2.right.val if node2.right else 0\n",
    "                elif not node1.right and node2.right:\n",
    "                    node1.right = TreeNode(node2.right.val)\n",
    "                \n",
    "                if node1.left and node2.left:\n",
    "                    tree1Que.append(node1.left)\n",
    "                    tree2Que.append(node2.left)\n",
    "                if node1.right and node2.right:\n",
    "                    tree1Que.append(node1.right)\n",
    "                    tree2Que.append(node2.right)\n",
    "        \n",
    "        return root1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:\n",
    "        # 递归终止条件: \n",
    "        #  但凡有一个节点为空, 就立刻返回另外一个. 如果另外一个也为None就直接返回None. \n",
    "        if not root1: \n",
    "            return root2\n",
    "        if not root2: \n",
    "            return root1\n",
    "        # 上面的递归终止条件保证了代码执行到这里root1, root2都非空. \n",
    "        root1.val += root2.val # 中\n",
    "        root1.left = self.mergeTrees(root1.left, root2.left) #左\n",
    "        root1.right = self.mergeTrees(root1.right, root2.right) # 右\n",
    "        \n",
    "        return root1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n",
    "        def func(root1, root2):\n",
    "            if not root1 or not root2:\n",
    "                return root1 if root1 else root2\n",
    "            root1.val += root2.val\n",
    "            root1.left = func(root1.left, root2.left)\n",
    "            root1.right = func(root1.right, root2.right)\n",
    "            return root1\n",
    "        return func(root1, root2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "class Solution(object):\n",
    "    def mergeTrees(self, t1, t2):\n",
    "        \"\"\"\n",
    "        :type t1: TreeNode\n",
    "        :type t2: TreeNode\n",
    "        :rtype: TreeNode\n",
    "        \"\"\"\n",
    "        # 如果两个二叉树中，有一个为空，则返回不为空的那个二叉树\n",
    "        if not t1:\n",
    "            return t2\n",
    "        if not t2:\n",
    "            return t1\n",
    "        # 否则将节点的值相加，并递归合并左右子树\n",
    "        merged_tree = TreeNode(t1.val + t2.val)\n",
    "        merged_tree.left = self.mergeTrees(t1.left, t2.left)\n",
    "        merged_tree.right = self.mergeTrees(t1.right, t2.right)\n",
    "        return merged_tree\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n",
    "        if not root1:\n",
    "            return root2\n",
    "        if not root2:\n",
    "            return root1\n",
    "        queue = [root1, root2]\n",
    "        while queue:\n",
    "            node1 = queue.pop(0)\n",
    "            node2 = queue.pop(0)\n",
    "            if node1.left and node2.left:\n",
    "                queue.append(node1.left)\n",
    "                queue.append(node2.left)\n",
    "            if node1.right and node2.right:\n",
    "                queue.append(node1.right)\n",
    "                queue.append(node2.right)\n",
    "            node1.val += node2.val\n",
    "            if not node1.left and node2.left:\n",
    "                node1.left = node2.left\n",
    "            if not node1.right and node2.right:\n",
    "                node1.right = node2.right\n",
    "\n",
    "        return root1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n",
    "        if not root1:\n",
    "            return root2\n",
    "        if not root2:\n",
    "            return root1\n",
    "\n",
    "        nodeList1 = collections.deque([root1])\n",
    "        nodeList2 = collections.deque([root2])\n",
    "\n",
    "        while nodeList1:\n",
    "            size1 = len(nodeList1)\n",
    "            for _ in range(size1):\n",
    "                cur1 = nodeList1.popleft()\n",
    "                cur2 = nodeList2.popleft()\n",
    "                cur1.val += cur2.val\n",
    "                if cur1.left:\n",
    "                    nodeList1.append(cur1.left)\n",
    "                    if cur2.left:\n",
    "                        nodeList2.append(cur2.left)\n",
    "                    else:\n",
    "                        nodeList1.pop()\n",
    "                else:\n",
    "                    if cur2.left:\n",
    "                        cur1.left = cur2.left\n",
    "                if cur1.right:\n",
    "                    nodeList1.append(cur1.right)\n",
    "                    if cur2.right:\n",
    "                        nodeList2.append(cur2.right)\n",
    "                    else:\n",
    "                        nodeList1.pop()\n",
    "                else:\n",
    "                    if cur2.right:\n",
    "                        cur1.right = cur2.right\n",
    "        return root1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n",
    "        if not root1:\n",
    "            return root2\n",
    "        if not root2:\n",
    "            return root1\n",
    "        \n",
    "        root = TreeNode(root1.val + root2.val)\n",
    "        queMerge, que = [root], [root1, root2]\n",
    "        while que:\n",
    "            node = queMerge.pop(0)\n",
    "            node1 = que.pop(0)\n",
    "            node2 = que.pop(0)\n",
    "            if node1.left and node2.left:\n",
    "                node.left = TreeNode(node1.left.val + node2.left.val)\n",
    "                queMerge.append(node.left)\n",
    "                que.append(node1.left)\n",
    "                que.append(node2.left)\n",
    "            elif node1.left:\n",
    "                node.left = node1.left\n",
    "            else:\n",
    "                node.left = node2.left\n",
    "            \n",
    "        \n",
    "            if node1.right and node2.right:\n",
    "                node.right = TreeNode(node1.right.val + node2.right.val)\n",
    "                queMerge.append(node.right)\n",
    "                que.append(node1.right)\n",
    "                que.append(node2.right)\n",
    "            elif node1.right:\n",
    "                node.right = node1.right\n",
    "            else:\n",
    "                node.right = node2.right\n",
    "\n",
    "        return root"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n",
    "        if not root1:\n",
    "            return root2\n",
    "        if not root2:\n",
    "            return root1\n",
    "        root1.val += root2.val\n",
    "        root1.left = self.mergeTrees(root1.left,root2.left)\n",
    "        root1.right = self.mergeTrees(root1.right,root2.right)\n",
    "        return root1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n",
    "        if not root1:\n",
    "            return root2\n",
    "        if not root2:\n",
    "            return root1\n",
    "        head = TreeNode(val=root1.val+root2.val)\n",
    "        head.left = self.mergeTrees(root1.left,root2.left)\n",
    "        head.right = self.mergeTrees(root1.right,root2.right)\n",
    "        return head"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for a binary tree node.\n",
    "# class TreeNode:\n",
    "#     def __init__(self, val=0, left=None, right=None):\n",
    "#         self.val = val\n",
    "#         self.left = left\n",
    "#         self.right = right\n",
    "class Solution:\n",
    "    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n",
    "        if not root1 and not root2:return\n",
    "        if not root1:root1=TreeNode(0)\n",
    "        elif not root2:root2=TreeNode(0)\n",
    "        ans=TreeNode(root1.val+root2.val)\n",
    "        ans.left=self.mergeTrees(root1.left,root2.left)\n",
    "        ans.right=self.mergeTrees(root1.right,root2.right)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1, l2):\n",
    "        \"\"\"\n",
    "        :type l1: ListNode\n",
    "        :type l2: ListNode\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        if l1 is None or l1.val is None:\n",
    "            return l2\n",
    "        if l2 is None or l2.val is None:\n",
    "            return l1\n",
    "        \n",
    "        curr_l1 = l1\n",
    "        curr_l2 = l2\n",
    "        result = ListNode(l1.val)\n",
    "        curr_result = result\n",
    "        while True:\n",
    "            if curr_l1 is None or curr_l1.val is None:\n",
    "                curr_result.next = curr_l2\n",
    "                break\n",
    "            if curr_l2 is None or curr_l2.val is None:\n",
    "                curr_result.next = curr_l1\n",
    "                break\n",
    "                \n",
    "            if curr_l1.val < curr_l2.val:\n",
    "                curr_result.next = ListNode(curr_l1.val)\n",
    "                curr_l1 = curr_l1.next\n",
    "            else:\n",
    "                curr_result.next = ListNode(curr_l2.val)\n",
    "                curr_l2 = curr_l2.next\n",
    "            curr_result = curr_result.next\n",
    "        \n",
    "        return result.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "#\r\n",
    "# @lc app=leetcode.cn id=21 lang=python3\r\n",
    "#\r\n",
    "# [21] 合并两个有序链表\r\n",
    "#\r\n",
    "# https://leetcode-cn.com/problems/merge-two-sorted-lists/description/\r\n",
    "#\r\n",
    "# algorithms\r\n",
    "# Easy (51.86%)\r\n",
    "# Total Accepted:    40.3K\r\n",
    "# Total Submissions: 77.8K\r\n",
    "# Testcase Example:  '[1,2,4]\\n[1,3,4]'\r\n",
    "#\r\n",
    "# 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 \r\n",
    "# \r\n",
    "# 示例：\r\n",
    "# \r\n",
    "# 输入：1->2->4, 1->3->4\r\n",
    "# 输出：1->1->2->3->4->4\r\n",
    "# \r\n",
    "# \r\n",
    "#\r\n",
    "# Definition for singly-linked list.\r\n",
    "# class ListNode:\r\n",
    "#     def __init__(self, x):\r\n",
    "#         self.val = x\r\n",
    "#         self.next = None\r\n",
    "\r\n",
    "class Solution:\r\n",
    "    def mergeTwoLists(self, l1, l2):\r\n",
    "        \"\"\"\r\n",
    "        :type l1: ListNode\r\n",
    "        :type l2: ListNode\r\n",
    "        :rtype: ListNode\r\n",
    "        \"\"\"\r\n",
    "        if not l1:\r\n",
    "            return l2\r\n",
    "        elif not l2:\r\n",
    "            return l1\r\n",
    "\r\n",
    "        if l1.val<l2.val:\r\n",
    "            head = l1\r\n",
    "            l1 = l1.next\r\n",
    "        else:\r\n",
    "            head = l2\r\n",
    "            l2 = l2.next\r\n",
    "        node = head\r\n",
    "\r\n",
    "        while l1 and l2:\r\n",
    "            if l1.val < l2.val:\r\n",
    "                node.next = l1\r\n",
    "                l1 = l1.next\r\n",
    "            else:\r\n",
    "                node.next = l2\r\n",
    "                l2 = l2.next\r\n",
    "            node = node.next\r\n",
    "        if l1 == None:\r\n",
    "            node.next = l2\r\n",
    "        else:\r\n",
    "            node.next = l1\r\n",
    "        return head\r\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1, l2):\n",
    "        \"\"\"\n",
    "        :type l1: ListNode\n",
    "        :type l2: ListNode\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        a,b = l1,l2\n",
    "        dummy = cur = ListNode(0)\n",
    "        \n",
    "        while a and b:\n",
    "            if a.val < b.val:\n",
    "                cur.next = ListNode(a.val)\n",
    "                a = a.next\n",
    "            else:\n",
    "                cur.next = ListNode(b.val)\n",
    "                b = b.next\n",
    "            cur = cur.next\n",
    "        if a:\n",
    "            cur.next = a\n",
    "        if b:\n",
    "            cur.next = b\n",
    "        return dummy.next\n",
    "                \n",
    "#         if not l1:\n",
    "#             return l2\n",
    "#         # If l2 is empty, return l1\n",
    "#         if not l2:\n",
    "#             return l1\n",
    "#         #If l1 val is lesser than l2, make temp point to l1 and move l1 to next element.\n",
    "#         #Get next element by recursively calling the function\n",
    "#         if l1.val <= l2.val:\n",
    "#             temp = l1\n",
    "#             temp.next = self.mergeTwoLists(l1.next, l2)\n",
    "\n",
    "#         #If l2 val is lesser than l2, make temp point to l2 and move l2 to next element.\n",
    "#         #Get next element by recursively calling the function\n",
    "#         else:\n",
    "#             temp = l2\n",
    "#             temp.next = self.mergeTwoLists(l1, l2.next)\n",
    "#         return temp\n",
    "#         if l1 is None:\n",
    "#             return l2\n",
    "#         if l2 is None:\n",
    "#             return l1\n",
    "\n",
    "#         if (l1.val < l2.val):\n",
    "#             l1.next = self.mergeTwoLists(l1.next, l2)\n",
    "#             return l1\n",
    "#         else:\n",
    "#             l2.next = self.mergeTwoLists(l2.next, l1)\n",
    "#             return l2 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "#\n",
    "# @lc app=leetcode.cn id=21 lang=python3\n",
    "#\n",
    "# [21] 合并两个有序链表\n",
    "#\n",
    "# https://leetcode-cn.com/problems/merge-two-sorted-lists/description/\n",
    "#\n",
    "# algorithms\n",
    "# Easy (52.01%)\n",
    "# Total Accepted:    41.8K\n",
    "# Total Submissions: 80.2K\n",
    "# Testcase Example:  '[1,2,4]\\n[1,3,4]'\n",
    "#\n",
    "# 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。\n",
    "#\n",
    "# 示例：\n",
    "#\n",
    "# 输入：1->2->4, 1->3->4\n",
    "# 输出：1->1->2->3->4->4\n",
    "#\n",
    "#\n",
    "#\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1, l2):\n",
    "        \"\"\"\n",
    "        :type l1: ListNode\n",
    "        :type l2: ListNode\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        if l1 is None and l2 is None:\n",
    "            return None\n",
    "        if l1 is None and l2 is not None:\n",
    "            return l2\n",
    "        if l1 is not None and l2 is None:\n",
    "            return l1\n",
    "        left = right = 0\n",
    "        result = []\n",
    "        l1_len = self.get_len(l1)\n",
    "        l2_len = self.get_len(l2)\n",
    "\n",
    "        print('l1_len', l1_len)\n",
    "        print('l2_len', l2_len)\n",
    "        while left <= l1_len and right <= l2_len:\n",
    "            if l1.val <= l2.val:\n",
    "                result.append(l1.val)\n",
    "                l1 = l1.next\n",
    "                left += 1\n",
    "            else:\n",
    "                result.append(l2.val)\n",
    "                l2 = l2.next\n",
    "                right += 1\n",
    "        while left <= l1_len:\n",
    "            result.append(l1.val)\n",
    "            l1 = l1.next\n",
    "            left += 1\n",
    "        while right <= l2_len:\n",
    "            result.append(l2.val)\n",
    "            l2 = l2.next\n",
    "            right += 1\n",
    "        return result\n",
    "\n",
    "    def get_len(self, l):\n",
    "        length = 0\n",
    "        while l.next != None:\n",
    "            length += 1\n",
    "            l = l.next\n",
    "        return length\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1, l2):\n",
    "        \"\"\"\n",
    "        :type l1: ListNode\n",
    "        :type l2: ListNode\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        if l1 is None:return l2\n",
    "        if l2 is None:return l1\n",
    "        \n",
    "        head=None\n",
    "        \n",
    "        if l1.val<l2.val:\n",
    "            head=l1\n",
    "            l1=l1.next\n",
    "        else:\n",
    "            head=l2\n",
    "            l2=l2.next\n",
    "            \n",
    "        temp=head\n",
    "        \n",
    "        while l1 and l2:\n",
    "            if l1.val<l2.val:\n",
    "                temp.next=l1\n",
    "                temp=temp.next\n",
    "                l1=l1.next\n",
    "            else:\n",
    "                temp.next=l2\n",
    "                temp=temp.next\n",
    "                l2=l2.next\n",
    "                \n",
    "        if l1 is None:\n",
    "            temp.next=l2\n",
    "        \n",
    "        if l2 is None:\n",
    "            temp.next=l1\n",
    "            \n",
    "        return head\n",
    "            \n",
    "            \n",
    "            \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        l=ListNode(0)\n",
    "        r=l\n",
    "        while l1!=None and l2!=None:\n",
    "            if l1.val<=l2.val:\n",
    "                l.next=l1\n",
    "                l=l.next\n",
    "                l1=l1.next\n",
    "            else:\n",
    "                l.next=l2\n",
    "                l=l.next\n",
    "                l2=l2.next\n",
    "        if l1!=None:\n",
    "            l.next=l1\n",
    "        if l2!=None:\n",
    "            l.next=l2\n",
    "        return r.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1, l2):\n",
    "        \"\"\"\n",
    "        :type l1: ListNode\n",
    "        :type l2: ListNode\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        head = merge = ListNode(0)\n",
    "        \n",
    "        while l1 and l2:\n",
    "            if l1.val < l2.val:\n",
    "                merge.next = l1\n",
    "                l1 = l1.next\n",
    "            else:\n",
    "                merge.next = l2\n",
    "                l2 = l2.next\n",
    "            print(merge.val)\n",
    "            merge = merge.next\n",
    "        if l1:\n",
    "            merge.next = l1\n",
    "        if l2:\n",
    "            merge.next = l2\n",
    "        \n",
    "        return head.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':\n",
    "        if l1 is None:\n",
    "            return l2\n",
    "        elif l2 is None:\n",
    "            return l1\n",
    "        elif l1 is None and l2 is None:\n",
    "            return None\n",
    "        \n",
    "        TheNode = ListNode(0)\n",
    "        FirstNode = TheNode\n",
    "        while True:\n",
    "            print(l1.val, l2.val)\n",
    "            if l1.val < l2.val:\n",
    "                TheNode.val = l1.val\n",
    "                if l1.next is None:\n",
    "                    TheNode.next = l2\n",
    "                    break\n",
    "                l1 = l1.next\n",
    "                TheNode.next = ListNode(0)\n",
    "                TheNode = TheNode.next\n",
    "            else:\n",
    "                TheNode.val = l2.val\n",
    "                if l2.next is None:\n",
    "                    TheNode.next = l1\n",
    "                    break\n",
    "                l2 = l2.next\n",
    "                TheNode.next = ListNode(0)\n",
    "                TheNode = TheNode.next\n",
    "        return FirstNode"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1, l2):\n",
    "        \"\"\"\n",
    "        :type l1: ListNode\n",
    "        :type l2: ListNode\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        tempNode=ListNode(0)\n",
    "        newNode=tempNode\n",
    "        while l1 or l2:\n",
    "            if not l1:\n",
    "                newNode.next=l2\n",
    "                l2=l2.next\n",
    "            elif not l2:\n",
    "                newNode.next=l1\n",
    "                l1=l1.next\n",
    "            else:\n",
    "                print(l1.val,l2.val)\n",
    "                if l1.val<=l2.val:\n",
    "                    newNode.next=l1\n",
    "                    l1=l1.next\n",
    "                else:\n",
    "                    newNode.next=l2\n",
    "                    l2=l2.next\n",
    "           \n",
    "            newNode=newNode.next\n",
    "        return tempNode.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        if l1 is None:\n",
    "            return l2\n",
    "        elif l2 is None:\n",
    "            return l1\n",
    "        elif l1.val<l2.val:\n",
    "            l1.next=self.mergeTwoLists(l1.next,l2)\n",
    "            return l1\n",
    "        else:\n",
    "            l2.next=self.mergeTwoLists(l2.next,l1)\n",
    "            return l2\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1, l2):\n",
    "        if l1 is None:\n",
    "            return l2\n",
    "        if l2 is None:\n",
    "            return l1 \n",
    "        if l1.val<=l2.val:\n",
    "            l1.next=self.mergeTwoLists(l1.next,l2)\n",
    "            return l1\n",
    "        else :\n",
    "            l2.next=self.mergeTwoLists(l2.next,l1)\n",
    "            return l2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        new_list = list()\n",
    "        if l1 is not None:\n",
    "            new_list += self.node_to_list(l1)\n",
    "        if l2 is not None:\n",
    "            new_list += self.node_to_list(l2)\n",
    "        new_list.sort()\n",
    "        new_list.reverse()\n",
    "        if new_list == list():\n",
    "            return None\n",
    "        else:\n",
    "            new_node = self.list_to_node(new_list)\n",
    "            return new_node\n",
    "        \n",
    "    def node_to_list(self, l: ListNode) -> list:\n",
    "        new_list = list()\n",
    "        tmp = l\n",
    "        while tmp.next is not None:\n",
    "            new_list.append(tmp.val)\n",
    "            tmp = tmp.next\n",
    "        new_list.append(tmp.val)\n",
    "        return new_list\n",
    "    \n",
    "    def list_to_node(self, new_list: list) -> ListNode:\n",
    "        head_node = ListNode(new_list[0])\n",
    "        for each in new_list[1:]:\n",
    "            tmp_node = ListNode(each)\n",
    "            tmp_node.next = head_node\n",
    "            head_node = tmp_node\n",
    "        return head_node\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1, l2):\n",
    "        res=ListNode(-1)\n",
    "        pre=res\n",
    "        res.val=None\n",
    "        while l1!=None and l2!=None:\n",
    "            if l1.val<=l2.val:\n",
    "                pre.next=l1\n",
    "                pre=l1\n",
    "                l1=l1.next\n",
    "            elif l2.val<=l1.val:\n",
    "                pre.next=l2\n",
    "                pre=l2\n",
    "                l2=l2.next\n",
    "        if l2==None:\n",
    "            pre.next=l1\n",
    "        elif l1==None:\n",
    "            pre.next=l2\n",
    "        return res.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        prehead = ListNode(-1)\n",
    "        prev = prehead\n",
    "        while l1 and l2:\n",
    "            if l1.val <= l2.val:\n",
    "                prev.next = l1\n",
    "                l1 = l1.next\n",
    "            else:\n",
    "                prev.next = l2\n",
    "                l2 = l2.next\n",
    "            prev = prev.next\n",
    "        prev.next = l1 if l1 else l2\n",
    "        #print(prev)\n",
    "        return prehead.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        \n",
    "        # dummy = ListNode(0)\n",
    "        # # 有个游标，标识 结果链表 的结尾\n",
    "        # move = dummy\n",
    "        # # l1 和 l2 都未遍历结束\n",
    "        # while l1 or l2:\n",
    "        #     # 如果 l1 的数值比较小\n",
    "        #     if l1.val <= l2.val:\n",
    "        #         # 把 l1 头部节点拼接到 结果链表 的结尾\n",
    "        #         move.next = l1\n",
    "        #         # l1 指向下一个节点\n",
    "        #         l1 = l1.next\n",
    "        #     else:\n",
    "        #         # 把 l2 头部节点拼接到 结果链表 的结尾\n",
    "        #         move.next = l2\n",
    "        #         # l2 指向下一个节点\n",
    "        #         l2 = l2.next\n",
    "        #     # 移动 结果链表 的结尾指针\n",
    "        #     move = move.next\n",
    "        # # l1 或者 l2 尚未使用完，拼接到 结果链表 的最后\n",
    "        # move.next = l1 if l1 else l2\n",
    "        # # 返回哑节点的下一个位置\n",
    "        # return dummy.next\n",
    "\n",
    "\n",
    "        l3=ListNode(0)\n",
    "        \n",
    "        move=l3\n",
    "        while l1 and l2:\n",
    "            # if not l1:\n",
    "            #     return l2\n",
    "            # if not l2:\n",
    "            #     return l1\n",
    "\n",
    "            if l1.val <= l2.val:\n",
    "                move.next=l1\n",
    "                \n",
    "                l1=l1.next\n",
    "            else:\n",
    "                move.next=l2\n",
    "                l2=l2.next\n",
    "                \n",
    "                \n",
    "            move = move.next\n",
    "        move.next = l1 if l1 else l2\n",
    "        return l3.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        if l1 and l2:\n",
    "            if l1.val > l2.val: l1, l2 = l2, l1\n",
    "            l1.next = self.mergeTwoLists(l1.next, l2)\n",
    "        return l1 or l2\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        infinity = 2**32\n",
    "        l3 = ListNode(-1)\n",
    "        p1 = l1\n",
    "        p2 = l2\n",
    "        p3 = l3\n",
    "        while p1 is not None or p2 is not None:\n",
    "            v1 = infinity if p1 is None else p1.val\n",
    "            v2 = infinity if p2 is None else p2.val\n",
    "            if v1 < v2:\n",
    "                p1 = p1.next\n",
    "                p3.next = ListNode(v1)\n",
    "            else:\n",
    "                p2 = p2.next\n",
    "                p3.next = ListNode(v2)\n",
    "            p3 = p3.next\n",
    "        return l3.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        if not l1:\n",
    "            return l2\n",
    "        elif not l2:\n",
    "            return l1\n",
    "        elif l1.val <= l2.val:\n",
    "            l1.next = self.mergeTwoLists(l1.next,l2)\n",
    "            return l1\n",
    "        else:\n",
    "            l2.next = self.mergeTwoLists(l1,l2.next)\n",
    "            return l2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        if not l1: return l2  # 终止条件，直到两个链表都空\n",
    "        if not l2: return l1\n",
    "        if l1.val <= l2.val:  # 递归调用\n",
    "            print(\"l1.val<=l2.val: \", l1)\n",
    "            l1.next = self.mergeTwoLists(l1.next,l2)\n",
    "            print(\"l1.val<=l2.val: \", l1)\n",
    "            return l1\n",
    "        else:\n",
    "            print(\"l1.val>l2.val: \", l2)   \n",
    "            l2.next = self.mergeTwoLists(l1,l2.next)\n",
    "            print(\"l1.val>l2.val: \", l2)            \n",
    "            return l2\n",
    "            \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "       temp = ListNode(0)\n",
    "       l3 = temp\n",
    "       while(l1!=None and l2!=None):\n",
    "            print(l1.val,l2.val)\n",
    "            if(l1.val<l2.val):\n",
    "                new =  ListNode(l1.val)\n",
    "                l3.next = new\n",
    "                l1 = l1.next\n",
    "            else:\n",
    "                new = ListNode(l2.val)\n",
    "                l3.next = new\n",
    "                l2 = l2.next\n",
    "            l3 = l3.next\n",
    "       #print(temp.next)\n",
    "       l3.next = l1 if l1!=None else l2\n",
    "       return temp.next\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        def printnode(head):\n",
    "            print(\"打印链表\")\n",
    "            pnode=ListNode(None)\n",
    "            \n",
    "            pnode=head\n",
    "\n",
    "##            pnode=head.next\n",
    "            while (pnode !=None ):\n",
    "                 print(pnode.val,end=' ')\n",
    "                 pnode=pnode.next\n",
    "                 print()\n",
    "            return\n",
    "        \n",
    "##        print(\"l1:  \",end='')\n",
    "##        printnode(l1)\n",
    "##        print(\"l2:  \",end='')\n",
    "##        printnode(l2)\n",
    "        \n",
    "        p1=ListNode(None)\n",
    "        link1=ListNode(None)\n",
    "        link2=ListNode(None)\n",
    "##        mcur=M\n",
    "\n",
    "##        if l1==None and l2 ==None:\n",
    "##           return None\n",
    "##        if l1.next!=None:\n",
    "##           link1=l1.next\n",
    "##        if l2.next!=None:\n",
    "##           link2=l2.next\n",
    "\n",
    "        if l1!=None and l1.val==None and l1.next!=None:\n",
    "            print(\"l1!=None and l1.val==None and l1.next!=None:\")\n",
    "            l1=l1.next\n",
    "        if l2!=None and l2.val==None and l2.next!=None:\n",
    "           print(\"l1!=None and l1.val==None and l1.next!=None:\")\n",
    "           l2=l2.next       \n",
    "            \n",
    "##\n",
    "\n",
    "        M1=ListNode(None)\n",
    "        mcur=ListNode(None)\n",
    "        #mcur=l1\n",
    "        M1=mcur\n",
    "        print(\"link2.val\",link2.val)\n",
    "        \n",
    "        if l1==None and l2 ==None:\n",
    "            return\n",
    "        elif  l1!=None and l2==None:\n",
    "            print(\" link1!=None and link2==None: \")\n",
    "            return l1\n",
    "        elif l1==None and l2!=None:\n",
    "            print(\" link1==None and link2!=None: \")            \n",
    "            return l2\n",
    "\n",
    "        \n",
    "        def meger (cur,link1,link2 ):\n",
    "            M1=ListNode(None)\n",
    "            mcur=ListNode(None)\n",
    "            mcur=cur\n",
    "\n",
    "            print(\"link1:  \",end='')\n",
    "            printnode(link1)\n",
    "            print(\"link2:  \",end='')\n",
    "            printnode(link2)\n",
    "        \n",
    "\n",
    "            #print(\"merge\",link1,link2)\n",
    "            \n",
    "\n",
    "            if link1!=None and link1.val==None:\n",
    "                link1=link1.next\n",
    "            if link2!=None and link2.val==None:\n",
    "                link2=link2.next\n",
    "            \n",
    "            \n",
    "            if link1 !=None and link2==None:\n",
    "                mcur.next=link1\n",
    "                print(\"link1 !=None and link2==None mcur\",mcur.val)\n",
    "                #return mcur\n",
    "                       \n",
    "            elif link1 ==None  and link2!=None:\n",
    "                mcur.next=link2\n",
    "                print(\"link1 ==None and link2!=None: mcur\",mcur.val)\n",
    "                #return mcur\n",
    "               \n",
    "            else:\n",
    "                if link1.val<=link2.val:\n",
    "                    mcur.next=link1\n",
    "                    print(\"link1.val \",link1.val)\n",
    "                    if link1.next !=None:\n",
    "                        link1=link1.next\n",
    "                    else:\n",
    "                        link1=None\n",
    "                    mcur=mcur.next               \n",
    "                    mcur=meger(mcur,link1,link2)\n",
    "                elif link1.val>link2.val:\n",
    "                    print(\"link2.val \",link2.val)\n",
    "                    mcur.next=link2\n",
    "                    if link2.next !=None:\n",
    "                        link2=link2.next\n",
    "                    else:\n",
    "                        link2=None\n",
    "                    mcur=mcur.next\n",
    "                    mcur=meger(mcur,link1,link2)\n",
    "            return mcur\n",
    "\n",
    "        meger(mcur,l1,l2)\n",
    "##        print(\" M1.next.val \",M1.val,M1.next.val,M1.next.next.val)\n",
    "        printnode(M1)\n",
    "##        \n",
    "        return  M1.next\n",
    "\n",
    "\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        p = ListNode()\n",
    "        c = p\n",
    "        while l1 and l2:\n",
    "            if l1.val <= l2.val:\n",
    "                p.next = ListNode(l1.val)\n",
    "                p = p.next\n",
    "                l1 = l1.next\n",
    "            else:\n",
    "                p.next = ListNode(l2.val)\n",
    "                p = p.next\n",
    "                l2 = l2.next\n",
    "        if l1:\n",
    "            p.next = l1\n",
    "        else:\n",
    "            p.next = l2\n",
    "        return c.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        a = ListNode(-1)\n",
    "        c = a\n",
    "        while list1 and list2:\n",
    "            if list1.val <= list2.val:\n",
    "                c.next = list1\n",
    "                list1 = list1.next\n",
    "            else:\n",
    "                c.next = list2\n",
    "                list2 = list2.next\n",
    "            c = c.next\n",
    "        c.next = list1 if list1 is not None else list2\n",
    "        return a.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        '''\n",
    "        # 利用递归，每次指向下一个\n",
    "        if not list1: return list2\n",
    "        if not list2: return list1\n",
    "        if list1.val <= list2.val:\n",
    "            list1.next = self.mergeTwoLists(list1.next, list2)\n",
    "            return list1\n",
    "        else:\n",
    "            list2.next = self.mergeTwoLists(list1, list2.next)\n",
    "            return list2\n",
    "        '''\n",
    "        dummy = ListNode(-1)\n",
    "        prev = dummy\n",
    "        while list1 and list2:\n",
    "            if list1.val <= list2.val:\n",
    "                prev.next = list1\n",
    "                list1 = list1.next\n",
    "            else:\n",
    "                prev.next = list2\n",
    "                list2 = list2.next\n",
    "            prev = prev.next\n",
    "        prev.next = list1 if list1 else list2\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        p, q = list1, list2\n",
    "        res = ListNode()\n",
    "        r = res\n",
    "        while p is not None and q is not None:\n",
    "            if p.val < q.val:\n",
    "                r.next = p\n",
    "                r = r.next\n",
    "                p = p.next\n",
    "            else:\n",
    "                r.next = q\n",
    "                r = r.next\n",
    "                q = q.next\n",
    "        while p is not None:\n",
    "            r.next = p\n",
    "            r = r.next\n",
    "            p = p.next\n",
    "        \n",
    "        while q is not None:\n",
    "            r.next = q\n",
    "            r = r.next\n",
    "            q = q.next\n",
    "        return res.next\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n",
    "        if not l1: return l2  # 终止条件，直到两个链表都空\n",
    "        if not l2: return l1\n",
    "        if l1.val <= l2.val:  # 递归调用\n",
    "            l1.next = self.mergeTwoLists(l1.next,l2)\n",
    "            return l1\n",
    "        else:\n",
    "            l2.next = self.mergeTwoLists(l1,l2.next)\n",
    "            return l2\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n",
    "\n",
    "        if list1 ==None:\n",
    "            return list2\n",
    "        if list2 == None:\n",
    "            return list1\n",
    "\n",
    "        l1 = ListNode(0,list1)\n",
    "        l2 = ListNode(0,list2)\n",
    "        l3 = ListNode()\n",
    "        cur1,cur2,cur3 = list1,list2,l3\n",
    "\n",
    "        while cur1 != None and cur2 != None:\n",
    "            if cur1.val <= cur2.val:\n",
    "                cur3.next = cur1  #cur3移动到cur1 \n",
    "                l1.next = cur1.next    #第一个链表删除第一个节点，自己指向自己\n",
    "                cur1 = l1.next          \n",
    "                cur3 = cur3.next      #合并的链表循环到尾部\n",
    "                cur3.next = None      #设置结束\n",
    "                print(l3)\n",
    "            else:\n",
    "                cur3.next = cur2  #cur3移动到cur1 \n",
    "                l2.next = cur2.next    #第一个链表删除第一个节点，自己指向自己\n",
    "                cur2 = l2.next          \n",
    "                cur3 = cur3.next      #合并的链表循环到尾部\n",
    "                cur3.next = None      #设置结束\n",
    "                print(l3)\n",
    "        if cur1 == None:\n",
    "            cur3.next = cur2\n",
    "        if cur2 == None:\n",
    "            cur3.next = cur1\n",
    "        return l3.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        l = list1\n",
    "        r = list2\n",
    "        if not l and not r:\n",
    "            return l\n",
    "        elif not l:\n",
    "            return r\n",
    "        elif not r:\n",
    "            return l\n",
    "        tempq = ListNode\n",
    "        temp = tempq\n",
    "        while l and r:\n",
    "            if l.val <= r.val:\n",
    "                temp.next = l\n",
    "                temp = l\n",
    "                l = l.next\n",
    "\n",
    "            else:\n",
    "                temp.next = r\n",
    "                temp = r\n",
    "                r = r.next\n",
    "        if not r:\n",
    "            temp.next = l\n",
    "        else:\n",
    "            temp.next = r\n",
    "        return tempq.next\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        node = ListNode()\n",
    "        fir = node\n",
    "        if not list1:\n",
    "            return list2\n",
    "        if not list2:\n",
    "            return list1\n",
    "        if not list1 and list2:\n",
    "            return []\n",
    "\n",
    "        while list1 and list2:\n",
    "            if list1.val < list2.val:\n",
    "                fir.next = ListNode(list1.val)\n",
    "                list1 = list1.next\n",
    "            else:\n",
    "                fir.next = ListNode(list2.val)\n",
    "                list2 = list2.next\n",
    "            fir = fir.next\n",
    "        if list1:\n",
    "            fir.next = list1\n",
    "        if list2:\n",
    "            fir.next = list2\n",
    "        return node.next\n",
    "        \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        dummy = ListNode()  # 新链表的头节点，是哑节点\n",
    "        cur = dummy  # 新链表的当前节点\n",
    "\n",
    "        # 遍历list1和list2，哪个小就把哪个加入新链表\n",
    "        while list1 is not None and list2 is not None:\n",
    "            if list1.val < list2.val:\n",
    "                cur.next = list1\n",
    "                list1 = list1.next\n",
    "            else:\n",
    "                cur.next = list2\n",
    "                list2 = list2.next\n",
    "            cur = cur.next\n",
    "\n",
    "        # list1和list2可能不等长，拼接剩下的链表\n",
    "        cur.next = list1 if list1 is not None else list2\n",
    "\n",
    "        return dummy.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def minCostConnectPoints(self, points: List[List[int]]) -> int:\n",
    "        n = len(points)\n",
    "        edge_list = []\n",
    "        for i in range(n):\n",
    "            for j in range(n):\n",
    "                if i == j:\n",
    "                    continue\n",
    "                edge_list.append((abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]), i, j))\n",
    "        edge_list.sort(key=lambda x:x[0])\n",
    "\n",
    "        fa_list = [i for i in range(n)]\n",
    "        \n",
    "        def find(x):\n",
    "            if x == fa_list[x]:\n",
    "                return x\n",
    "            else:\n",
    "                fa_list[x] = find(fa_list[x])\n",
    "                return fa_list[x]\n",
    "        \n",
    "        def merge(x, y):\n",
    "            fa_list[find(x)] = find(y)\n",
    "        \n",
    "        ans = n_len = 0\n",
    "        for d, i, j in edge_list:\n",
    "            if find(i) == find(j):\n",
    "                continue\n",
    "            merge(i, j)\n",
    "            n_len += 1\n",
    "            ans += d\n",
    "            if n_len == n - 1:\n",
    "                break\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n",
    "        u = self.Union()\n",
    "        for item in allowedSwaps:\n",
    "            u.merge(item[0], item[1])\n",
    "\n",
    "        m = {}\n",
    "        for i in range(0, len(source)):\n",
    "            idx = u.search(i)\n",
    "            if m.get(idx) is None:\n",
    "                m[idx] = {}\n",
    "            if m[idx].get(source[i]) is None:\n",
    "                m[idx][source[i]] = 1\n",
    "            else:\n",
    "                m[idx][source[i]] += 1\n",
    "        for i in range(0, len(target)):\n",
    "            idx = u.search(i)\n",
    "            if m[idx].get(target[i]) is not None:\n",
    "                m[idx][target[i]] -= 1\n",
    "                if m[idx][target[i]] == 0:\n",
    "                    del m[idx][target[i]]\n",
    "        sum = 0\n",
    "        for k in m:\n",
    "            for v in m[k]:\n",
    "                sum += m[k][v]\n",
    "        return sum\n",
    "\n",
    "\n",
    "    class Union:\n",
    "        def __init__(self):\n",
    "            self.map = {}\n",
    "\n",
    "        def merge(self, i, j: int):\n",
    "            pi, pj = self.search(i), self.search(j)\n",
    "            if pi != pj:\n",
    "                self.map[pj] = pi\n",
    "\n",
    "        def search(self, i: int) -> int:\n",
    "            pi = self.map.get(i)\n",
    "            if pi is None:\n",
    "                return i\n",
    "            ppi = self.map.get(pi)\n",
    "            if ppi != pi:\n",
    "                self.map[i] = self.search(pi)\n",
    "            return self.map[i]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n",
    "        n = len(source)\n",
    "        fa = [i for i in range(n)]\n",
    "        sz = [1] * n \n",
    "        \n",
    "        def find(x):\n",
    "            if fa[x] != x:\n",
    "                fa[x] = find(fa[x])\n",
    "            return fa[x]\n",
    "        \n",
    "        def merge(x, y):\n",
    "            fx, fy = find(x), find(y)\n",
    "            if fx != fy:\n",
    "                fa[fx] = fy\n",
    "                sz[fy] += sz[fx]\n",
    "            \n",
    "        for x, y in allowedSwaps:\n",
    "            merge(x, y)\n",
    "        ans = 0\n",
    "        g1, g2 = defaultdict(Counter), defaultdict(Counter)\n",
    "        for i, x, y in zip(range(n), source, target):\n",
    "            if i == find(i) and sz[i] == 1:\n",
    "                ans += x != y\n",
    "            else:\n",
    "                g1[find(i)][x] += 1\n",
    "                g2[find(i)][y] += 1\n",
    "        cnt = 0\n",
    "        for k in g1.keys():\n",
    "            for kk in (set(g1[k].keys()) | set(g2[k].keys())):\n",
    "                cnt += abs(g1[k][kk]-g2[k][kk])\n",
    "        ans += cnt // 2\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import *\n",
    "'''\n",
    "--- 从此处复制 ---\n",
    "'''\n",
    "class IdentityDefaultDict(defaultdict):\n",
    "    '''\n",
    "    该类用于处理并查集初始化的恒等映射\n",
    "    '''\n",
    "    def __missing__(self, key):\n",
    "        return key\n",
    "\n",
    "class UnionFind:\n",
    "    def __init__(self, n=None):\n",
    "        self.parent = IdentityDefaultDict()\n",
    "        if n: self.parent = list(range(n))\n",
    "    def find(self, x):\n",
    "        if self.parent[x] != x: self.parent[x] = self.find(self.parent[x])\n",
    "        return self.parent[x]\n",
    "    def merge(self, x, y):\n",
    "        x, y = self.find(x), self.find(y)\n",
    "        if x != y: self.parent[x] = y\n",
    "    def count_groups(self):\n",
    "        return len(set(self.find(x) for x in self.parent))\n",
    "\n",
    "class Solution:\n",
    "    def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n",
    "        uf = UnionFind()\n",
    "        for x, y in allowedSwaps:\n",
    "            uf.merge(x, y)\n",
    "        n = len(source)\n",
    "        g1, g2 = defaultdict(list), defaultdict(list)\n",
    "        for i in range(n):\n",
    "            g1[uf.find(i)].append(source[i])\n",
    "            g2[uf.find(i)].append(target[i])\n",
    "\n",
    "        ans = 0\n",
    "        for k in g1:\n",
    "            c1, c2 = Counter(g1[k]), Counter(g2[k])\n",
    "            for k2 in set(list(c1.keys()) + list(c2.keys())):\n",
    "                ans += max(c1[k2], c2[k2]) - min(c1[k2], c2[k2])\n",
    "            \n",
    "        return ans // 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n",
    "        initial = set(initial)\n",
    "        def find(x):#并查集\n",
    "            if x not in cache:\n",
    "                cache[x] = x\n",
    "            if cache[x] != x:\n",
    "                cache[x] = find(cache[x])\n",
    "            return cache[x]\n",
    "        def merge(x, y):\n",
    "            cache[find(x)] = find(y)\n",
    "        n = len(graph)\n",
    "        cache = {}\n",
    "        for i in range(n):\n",
    "            for j in range(n):\n",
    "                if i != j and i not in initial and j not in initial and graph[i][j] == 1:\n",
    "                    merge(i, j)\n",
    "        d = {}#计算每个节点集合的数量\n",
    "        for i in range(n):\n",
    "            i = find(i)\n",
    "            d[i] = d.get(i, 0) + 1\n",
    "        s = set(d.keys())\n",
    "        cnt = {}#存储每个节点集合能被多少个感染节点所连接\n",
    "        for i in initial:\n",
    "            c = 0\n",
    "            s1 = set([find(j) for j in range(n) if j not in initial and graph[i][j] == 1])\n",
    "            for j in s1:\n",
    "                cnt[j] = cnt.get(j, 0) + 1\n",
    "        m = -1\n",
    "        for i in sorted(initial):#升序遍历,如果有多个节点需要返回最小的\n",
    "            c = 0\n",
    "            s1 = set([find(j) for j in range(n) if j not in initial and graph[i][j] == 1])\n",
    "            for j in s1:\n",
    "                if cnt[j] == 1:#如果节点集合值为1,说明去除本节点后这个集合不会被感染,进行累加计数\n",
    "                    c += d[j]\n",
    "            if c > m:#当不会被感染的集合数量越大说明被感染节点总数越小\n",
    "                m = c\n",
    "                res = i\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from math import *\n",
    "from queue import PriorityQueue,Queue\n",
    "from typing import *\n",
    "from heapq import *\n",
    "from functools import lru_cache,cache\n",
    "from string import *\n",
    "# by hangpengjie\n",
    "class UF:\n",
    "    def __init__(self,n:int) -> None:\n",
    "        self.parent = [i for i in range(n)]\n",
    "        self.rank = [1 for _ in range(n)]\n",
    "    def find(self,x:int)->int:\n",
    "        if self.parent[x] == x:\n",
    "            return x\n",
    "        self.parent[x] = self.find(self.parent[x])\n",
    "        return self.parent[x]\n",
    "    def merge(self,x:int,y:int)->None:\n",
    "        x = self.find(x)\n",
    "        y = self.find(y)\n",
    "        if x == y:\n",
    "            return\n",
    "        self.rank[y] += self.rank[x]\n",
    "        self.rank[x] = 0\n",
    "        self.parent[x] = y\n",
    "class Solution:\n",
    "    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n",
    "        n = len(graph)\n",
    "        clean = [1] * n\n",
    "        # 标记出受污染的软件\n",
    "        for t in initial:\n",
    "            clean[t] = 0\n",
    "        uf = UF(n)\n",
    "        # 建立未被污染的软件的并查集\n",
    "        for i in range(n):\n",
    "            if clean[i]:\n",
    "                for j in range(n):\n",
    "                    if clean[j]:\n",
    "                        if graph[i][j]:\n",
    "                            uf.merge(i,j)\n",
    "        # 统计并查集中每个集合和哪些受污染的软件连接\n",
    "        mp = dict()\n",
    "        for i in range(n):\n",
    "            if not clean[i]:\n",
    "                for j in range(n):\n",
    "                    if clean[j] and graph[i][j]:\n",
    "                        p = uf.find(j)\n",
    "                        if p not in mp:\n",
    "                            mp[p] = set()\n",
    "                        mp[p].add(i)\n",
    "        # 只记录集合只和一个受污染软件连接的受污染软件能够贡献的答案，即集合的秩\n",
    "        d = dict()\n",
    "        for k,v in mp.items():\n",
    "            if len(v) == 1:\n",
    "                t = v.pop()\n",
    "                if t not in d:\n",
    "                    d[t] = 0\n",
    "                d[t] += uf.rank[uf.find(k)]\n",
    "        initial.sort()\n",
    "        # 初始化答案\n",
    "        res = initial[0]\n",
    "        cnt = 0\n",
    "        for k,v in d.items():\n",
    "            if v == cnt and k < res:\n",
    "                res = k\n",
    "            elif v > cnt:\n",
    "                cnt = v\n",
    "                res = k\n",
    "        return res\n",
    "    \n",
    "s = Solution()\n",
    "s.minMalwareSpread([[1,0,0,0,0,0,0,0,0],[0,1,0,0,0,0,0,0,1],[0,0,1,0,0,0,0,0,0],[0,0,0,1,0,0,0,0,1],[0,0,0,0,1,0,1,1,1],[0,0,0,0,0,1,0,0,1],[0,0,0,0,1,0,1,1,0],[0,0,0,0,1,0,1,1,0],[0,1,0,1,1,1,0,0,1]],\n",
    "                   [8,4,2,0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n",
    "        n = len(graph)\n",
    "        fa = list(range(n))\n",
    "        sz, szbad, bad = [1] * n, [0] * n, [0] * n\n",
    "        for i in initial: szbad[i], bad[i] = 1, 1\n",
    "        def getfa(x):\n",
    "            root = x\n",
    "            while root != fa[root]:\n",
    "                root = fa[root]\n",
    "            while x != fa[x]:\n",
    "                fa[x], x = root, fa[x] \n",
    "            return x\n",
    "\n",
    "        def merge(a, b):\n",
    "            pa, pb = getfa(a), getfa(b)\n",
    "            if pa != pb:\n",
    "                if sz[pa] > sz[pb]: pa, pb = pb, pa\n",
    "                sz[pb] += sz[pa]\n",
    "                sz[pa] = 0\n",
    "                szbad[pb] += szbad[pa]\n",
    "                szbad[pa] = 0\n",
    "                fa[pa] = pb\n",
    "        d = {}\n",
    "        g = [[] for _ in range(n)]\n",
    "        for i in range(n):\n",
    "            for j in range(0, i + 1):\n",
    "                if graph[i][j] == 1:\n",
    "                    g[i].append(j)\n",
    "                    g[j].append(i)\n",
    "                    if not bad[i] and not bad[j]:\n",
    "                        merge(i, j)\n",
    "        groupGood = set()\n",
    "        for i in range(n):\n",
    "            groupGood.add(getfa(i))\n",
    "        for i in initial:\n",
    "            s = set()\n",
    "            for j in g[i]:\n",
    "                pj = getfa(j)\n",
    "                if pj not in s:\n",
    "                    szbad[pj] += 1\n",
    "                    s.add(pj)\n",
    "        \n",
    "        t = [0] * n\n",
    "        evil = set(initial)\n",
    "        for i in initial:\n",
    "            s = set()\n",
    "            for j in g[i]:\n",
    "                if j in evil: continue\n",
    "                pj = getfa(j)\n",
    "                if pj not in s and szbad[pj] == 1:\n",
    "                    t[i] += sz[pj]\n",
    "                    s.add(pj)\n",
    "        ans = initial[-1]\n",
    "        M = 0\n",
    "        for i in sorted(initial, reverse=True):\n",
    "            if t[i] > M:\n",
    "                M, ans = t[i], i\n",
    "            elif t[i] == M:\n",
    "                ans = i\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\r\n",
    "        initial = set(initial)\r\n",
    "        def find(x):#并查集\r\n",
    "            if x not in cache:\r\n",
    "                cache[x] = x\r\n",
    "            if cache[x] != x:\r\n",
    "                cache[x] = find(cache[x])\r\n",
    "            return cache[x]\r\n",
    "        def merge(x, y):\r\n",
    "            cache[find(x)] = find(y)\r\n",
    "        n = len(graph)\r\n",
    "        cache = {}\r\n",
    "        for i in range(n):\r\n",
    "            for j in range(n):\r\n",
    "                if i != j and i not in initial and j not in initial and graph[i][j] == 1:\r\n",
    "                    merge(i, j)\r\n",
    "        d = {}#计算每个节点集合的数量\r\n",
    "        for i in range(n):\r\n",
    "            i = find(i)\r\n",
    "            d[i] = d.get(i, 0) + 1\r\n",
    "        s = set(d.keys())\r\n",
    "        cnt = {}#存储每个节点集合能被多少个感染节点所连接\r\n",
    "        for i in initial:\r\n",
    "            c = 0\r\n",
    "            s1 = set([find(j) for j in range(n) if j not in initial and graph[i][j] == 1])#计算的是感染节点数,避免重复计数采取集合\r\n",
    "            for j in s1:\r\n",
    "                cnt[j] = cnt.get(j, 0) + 1\r\n",
    "        m = -1\r\n",
    "        for i in sorted(initial):#升序遍历,如果有多个节点需要返回最小的\r\n",
    "            c = 0\r\n",
    "            s1 = set([find(j) for j in range(n) if j not in initial and graph[i][j] == 1])\r\n",
    "            for j in s1:\r\n",
    "                if cnt[j] == 1:#如果节点集合值为1,说明去除本节点后这个集合不会被感染,进行累加计数\r\n",
    "                    c += d[j]\r\n",
    "            if c > m:#当不会被感染的集合数量越大说明被感染节点总数越小\r\n",
    "                m = c\r\n",
    "                res = i\r\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n",
    "        n = len(graph)\n",
    "        fa = list(range(n))\n",
    "        sz, szbad, bad = [1] * n, [0] * n, [0] * n\n",
    "        for i in initial: szbad[i], bad[i] = 1, 1\n",
    "        def getfa(x):\n",
    "            root = x\n",
    "            while root != fa[root]:\n",
    "                root = fa[root]\n",
    "            while x != fa[x]:\n",
    "                fa[x], x = root, fa[x] \n",
    "            return x\n",
    "\n",
    "        def merge(a, b):\n",
    "            pa, pb = getfa(a), getfa(b)\n",
    "            if pa != pb:\n",
    "                if sz[pa] > sz[pb]: pa, pb = pb, pa\n",
    "                sz[pb] += sz[pa]\n",
    "                sz[pa] = 0\n",
    "                szbad[pb] += szbad[pa]\n",
    "                szbad[pa] = 0\n",
    "                fa[pa] = pb\n",
    "        d = {}\n",
    "        g = [[] for _ in range(n)]\n",
    "        for i in range(n):\n",
    "            for j in range(0, i+1):\n",
    "                if graph[i][j] == 1:\n",
    "                    merge(i, j)\n",
    "                    g[i].append(j)\n",
    "                    g[j].append(i)\n",
    "                    # if i != j: print(i, j)\n",
    "        \n",
    "        # 割点\n",
    "        dfn, low, cut = [-1]*n, [-1]*n, [False]*n\n",
    "        idx, count = 0,0\n",
    "\n",
    "        def tarjan(x, fa):\n",
    "            nonlocal idx, count\n",
    "            child = 0\n",
    "            dfn[x], low[x] = idx, idx\n",
    "            idx+=1\n",
    "            for y in g[x]:\n",
    "                if dfn[y]==-1:\n",
    "                    child += 1\n",
    "                    tarjan(y,x)\n",
    "                    low[x] = min(low[x], low[y])\n",
    "                    if fa!=-1 and low[y]>=dfn[x] and cut[x]==False:\n",
    "                        cut[x] = True\n",
    "                        count+=1\n",
    "                else:\n",
    "                    if y!=fa:\n",
    "                        low[x] = min(low[x], dfn[y])\n",
    "            if fa==-1 and child>=2 and cut[x]==False:\n",
    "                cut[x] = True\n",
    "                count += 1\n",
    "            pass\n",
    "        \n",
    "        for i in range(n):\n",
    "            if dfn[i]==-1: tarjan(i,-1)\n",
    "\n",
    "        ans = initial[-1]\n",
    "        M = 0\n",
    "\n",
    "        # 求割点的未感染子树的节点个数和\n",
    "        def dfs(root, u, p):\n",
    "            vis[u] = 1\n",
    "            res = int(root != u)\n",
    "            if u != root and bad[u]:\n",
    "                return 0\n",
    "            f = False\n",
    "            for x in g[u]:\n",
    "                if vis[x]: continue\n",
    "                t = dfs(root, x, u)\n",
    "                if t == 0 and u != root:\n",
    "                    f = True\n",
    "                res += t\n",
    "            if f: return 0\n",
    "            return res\n",
    "\n",
    "        for i in range(n-1, -1, -1):\n",
    "            if bad[i] == 0:continue\n",
    "            t = getfa(i)\n",
    "            if szbad[t] == 1:\n",
    "                if sz[t] - 1 >= M: ans, M = i, sz[t] - 1\n",
    "            elif szbad[t] > 1:\n",
    "                if M == 0: ans = i\n",
    "                if cut[i]:\n",
    "                    vis = [0] * n\n",
    "                    num = dfs(i, i, -1)\n",
    "                    # print(i, num)\n",
    "                    if num >= M: ans, M = i, num\n",
    "            # print(M, i, t, szbad[t], sz[t], cut[i])\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class BCJ:\n",
    "    def __init__(self):\n",
    "        self.father = {}\n",
    "        self.count = {}\n",
    "    def find(self, x):\n",
    "        root = x\n",
    "        while self.father[root] != None:\n",
    "            root = self.father[root]\n",
    "        while x != root:\n",
    "            tmp_father = self.father[x]\n",
    "            self.father[x] = root\n",
    "            x = tmp_father\n",
    "        return root\n",
    "    def add(self, x):\n",
    "        if x not in self.father:\n",
    "            self.father[x] = None\n",
    "            self.count[x] = 1\n",
    "    def merge(self, x, y):\n",
    "        root_x, root_y = self.find(x), self.find(y)\n",
    "        if self.count[root_x] < self.count[root_y]:\n",
    "            self.father[root_x] = root_y\n",
    "            self.count[root_y] += self.count[root_x]\n",
    "        elif root_x != root_y:\n",
    "            self.father[root_y] = root_x\n",
    "            self.count[root_x] += self.count[root_y]\n",
    "class Solution:\n",
    "    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n",
    "        bcj = BCJ()\n",
    "        for i in range(len(graph)):\n",
    "            bcj.add(i)\n",
    "            for j in range(len(graph[i])):\n",
    "                bcj.add(j)\n",
    "                if graph[i][j]:\n",
    "                    bcj.merge(i, j)\n",
    "        max_index = -1\n",
    "        max_value = 0\n",
    "        father_count_dict = {}\n",
    "        initial.sort()\n",
    "        for init in initial:\n",
    "            current_root = bcj.find(init)\n",
    "            if current_root not in father_count_dict:\n",
    "                father_count_dict[current_root] = 1\n",
    "            else:\n",
    "                father_count_dict[current_root] += 1\n",
    "        for i in range(len(initial)):\n",
    "            current_root = bcj.find(initial[i])\n",
    "            if father_count_dict[current_root] > 1:\n",
    "                continue\n",
    "            if max_value < bcj.count[current_root]:\n",
    "                max_value = bcj.count[current_root]\n",
    "                max_index = initial[i]\n",
    "        return max_index if max_index != -1 else initial[0]\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n",
    "        n = len(graph)\n",
    "        fa = list(range(n))\n",
    "        sz, szbad, bad = [1] * n, [0] * n, [0] * n\n",
    "        for i in initial: szbad[i], bad[i] = 1, 1\n",
    "        def getfa(x):\n",
    "            root = x\n",
    "            while root != fa[root]:\n",
    "                root = fa[root]\n",
    "            while x != fa[x]:\n",
    "                fa[x], x = root, fa[x] \n",
    "            return x\n",
    "\n",
    "        def merge(a, b):\n",
    "            pa, pb = getfa(a), getfa(b)\n",
    "            if pa != pb:\n",
    "                if sz[pa] > sz[pb]: pa, pb = pb, pa\n",
    "                sz[pb] += sz[pa]\n",
    "                sz[pa] = 0\n",
    "                szbad[pb] += szbad[pa]\n",
    "                szbad[pa] = 0\n",
    "                fa[pa] = pb\n",
    "        for i in range(n):\n",
    "            for j in range(0, i+1):\n",
    "                if graph[i][j] == 1:\n",
    "                    merge(i, j)\n",
    "        \n",
    "        ans = initial[-1]\n",
    "        M = 0\n",
    "\n",
    "        for i in range(n-1, -1, -1):\n",
    "            if bad[i] == 0: continue\n",
    "            t = getfa(i)\n",
    "            if szbad[t] == 1:\n",
    "                if sz[t] >= M: ans, M = i, sz[t]\n",
    "            elif szbad[t] > 1:\n",
    "                if M == 0: ans = i\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n",
    "        n = len(graph)\n",
    "        initial.sort()\n",
    "\n",
    "        fa = [i for i in range(n)]\n",
    "        sz = [1 for i in range(n)]\n",
    "\n",
    "        def find(i):\n",
    "            if fa[i] == i:\n",
    "                return i\n",
    "            else:\n",
    "                fa[i] = find(fa[i])\n",
    "                return fa[i]\n",
    "\n",
    "        def merge(i, j):\n",
    "            fi = find(i)\n",
    "            fj = find(j)\n",
    "\n",
    "            if fi == fj:\n",
    "                return\n",
    "\n",
    "            if sz[i] > sz[j]:\n",
    "                fi, fj = fj, fi\n",
    "\n",
    "            fa[fi] = fj\n",
    "            sz[fj] += sz[fi]\n",
    "\n",
    "        for i in range(n):\n",
    "            for j in range(n):\n",
    "                if graph[i][j] == 1:\n",
    "                    merge(i, j)\n",
    "\n",
    "        d = defaultdict(list)\n",
    "        for x in initial:\n",
    "            d[find(x)].append(x)\n",
    "\n",
    "        ret = -1\n",
    "        ma = 0\n",
    "\n",
    "        # print(fa, sz, d)\n",
    "\n",
    "        for x in initial:\n",
    "            if len(d[find(x)]) == 1:\n",
    "                if ma < sz[find(x)]:\n",
    "                    ma = sz[find(x)]\n",
    "                    ret = x\n",
    "\n",
    "        if ret == -1:\n",
    "            ret = min(initial)\n",
    "            \n",
    "        return ret\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n",
    "        n = len(graph)\n",
    "        fa = list(range(n))\n",
    "        sz, szbad, bad = [1] * n, [0] * n, [0] * n\n",
    "        for i in initial: szbad[i], bad[i] = 1, 1\n",
    "        def getfa(x):\n",
    "            root = x\n",
    "            while root != fa[root]:\n",
    "                root = fa[root]\n",
    "            while x != fa[x]:\n",
    "                fa[x], x = root, fa[x] \n",
    "            return x\n",
    "\n",
    "        def merge(a, b):\n",
    "            pa, pb = getfa(a), getfa(b)\n",
    "            if pa != pb:\n",
    "                if sz[pa] > sz[pb]: pa, pb = pb, pa\n",
    "                sz[pb] += sz[pa]\n",
    "                sz[pa] = 0\n",
    "                szbad[pb] += szbad[pa]\n",
    "                szbad[pa] = 0\n",
    "                fa[pa] = pb\n",
    "        d = {}\n",
    "        g = [[] for _ in range(n)]\n",
    "        for i in range(n):\n",
    "            for j in range(0, i+1):\n",
    "                if graph[i][j] == 1:\n",
    "                    merge(i, j)\n",
    "                    g[i].append(j)\n",
    "                    g[j].append(i)\n",
    "                    # if i != j: print(i, j)\n",
    "        \n",
    "\n",
    "        \n",
    "        ans = initial[-1]\n",
    "        M = 0\n",
    "\n",
    "        # 求割点的未感染子树的节点个数和\n",
    "        def dfs(root, u, p):\n",
    "            vis[u] = 1\n",
    "            res = int(root != u)\n",
    "            if u != root and bad[u]:\n",
    "                return 0\n",
    "            f = False\n",
    "            for x in g[u]:\n",
    "                if vis[x]: continue\n",
    "                t = dfs(root, x, u)\n",
    "                if t == 0 and u != root:\n",
    "                    f = True\n",
    "                res += t\n",
    "            if f: return 0\n",
    "            return res\n",
    "\n",
    "        for i in range(n-1, -1, -1):\n",
    "            if bad[i] == 0: continue\n",
    "            t = getfa(i)\n",
    "            if szbad[t] == 1:\n",
    "                if sz[t] >= M: ans, M = i, sz[t]\n",
    "            elif szbad[t] > 1:\n",
    "                if M == 0: ans = i\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# 借助并查集按照人物遍历每一条边\n",
    "class UnionFind:\n",
    "    def __init__(self,size):\n",
    "        self.father = [None] * (size+1)\n",
    "        self.num_of_sets = size\n",
    "    \n",
    "    def find(self,x):\n",
    "        if self.father[x] is None: return x\n",
    "        self.father[x] = self.find(self.father[x])\n",
    "        return self.father[x]\n",
    "    \n",
    "    def is_connected(self,x,y):\n",
    "        return self.find(x) == self.find(y)\n",
    "    \n",
    "    def merge(self,x,y):\n",
    "        self.father[self.find(x)] = self.find(y)\n",
    "        self.num_of_sets -= 1\n",
    "\n",
    "class Solution:\n",
    "    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n",
    "        res = 0\n",
    "        uf_alice = UnionFind(n)\n",
    "        uf_bob = UnionFind(n)\n",
    "        for _type,n1,n2 in edges:\n",
    "            if _type == 3:\n",
    "                if not uf_alice.is_connected(n1,n2):\n",
    "                    uf_alice.merge(n1,n2)\n",
    "                    uf_bob.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "        for _type,n1,n2 in edges:\n",
    "            if _type == 1:\n",
    "                if not uf_alice.is_connected(n1,n2):\n",
    "                    uf_alice.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "            if _type == 2:\n",
    "                if not uf_bob.is_connected(n1,n2):\n",
    "                    uf_bob.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "\n",
    "        return -1 if uf_alice.num_of_sets * uf_bob.num_of_sets > 1 else res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class UnionFind:\n",
    "    def __init__(self,size):\n",
    "        self.fa = [None] * (size + 1)\n",
    "        self.num_of_sets = size\n",
    "    \n",
    "    def find(self,x):\n",
    "        if self.fa[x] is None:\n",
    "            return x\n",
    "        self.fa[x] = self.find(self.fa[x])\n",
    "        return self.fa[x]\n",
    "    \n",
    "    def is_connected(self,x,y):\n",
    "        return self.find(x) == self.find(y)\n",
    "    \n",
    "    def merge(self,x,y):\n",
    "        self.fa[self.find(x)] = self.find(y)\n",
    "        self.num_of_sets -= 1\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n",
    "        res = 0\n",
    "        uf_alice = UnionFind(n)\n",
    "        uf_bob = UnionFind(n)\n",
    "        for t , a, b in edges:\n",
    "            if t == 3:\n",
    "                if not uf_alice.is_connected(a,b):\n",
    "                    uf_alice.merge(a,b)\n",
    "                    uf_bob.merge(a,b)\n",
    "                else:\n",
    "                    res +=1\n",
    "\n",
    "        for t , a, b in edges:\n",
    "            if t == 1:\n",
    "                if not uf_alice.is_connected(a,b):\n",
    "                    uf_alice.merge(a,b)\n",
    "                else:\n",
    "                    res +=1\n",
    "            elif t == 2:\n",
    "                if not uf_bob.is_connected(a,b):\n",
    "                    uf_bob.merge(a,b)\n",
    "                else:\n",
    "                    res +=1\n",
    "        return -1 if uf_alice.num_of_sets * uf_bob.num_of_sets > 1 else res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class UnionFind:\n",
    "    def __init__(self,size):\n",
    "        self.father = [None] * (size+1)\n",
    "        self.num_of_sets = size\n",
    "    \n",
    "    def find(self,x):\n",
    "        if self.father[x] is None: return x\n",
    "        self.father[x] = self.find(self.father[x])\n",
    "        return self.father[x]\n",
    "    \n",
    "    def is_connected(self,x,y):\n",
    "        return self.find(x) == self.find(y)\n",
    "    \n",
    "    def merge(self,x,y):\n",
    "        self.father[self.find(x)] = self.find(y)\n",
    "        self.num_of_sets -= 1\n",
    "\n",
    "class Solution:\n",
    "    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n",
    "        res = 0\n",
    "        uf_alice = UnionFind(n)\n",
    "        uf_bob = UnionFind(n)\n",
    "        for _type,n1,n2 in edges:\n",
    "            if _type == 3:\n",
    "                if not uf_alice.is_connected(n1,n2):\n",
    "                    uf_alice.merge(n1,n2)\n",
    "                    uf_bob.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "        for _type,n1,n2 in edges:\n",
    "            if _type == 1:\n",
    "                if not uf_alice.is_connected(n1,n2):\n",
    "                    uf_alice.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "            if _type == 2:\n",
    "                if not uf_bob.is_connected(n1,n2):\n",
    "                    uf_bob.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "\n",
    "        return -1 if uf_alice.num_of_sets * uf_bob.num_of_sets > 1 else res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class UnionFind:\n",
    "    def __init__(self, n):\n",
    "        self.parent = [i for i in range(n)]\n",
    "        self.rank = [1] * n\n",
    "\n",
    "    def find(self, u):\n",
    "        if self.parent[u] == u:\n",
    "            return u\n",
    "        self.parent[u] = self.find(self.parent[u])\n",
    "        return self.parent[u]\n",
    "\n",
    "    def merge(self, u, v):\n",
    "        u = self.find(u)\n",
    "        v = self.find(v)\n",
    "        if u == v:\n",
    "            return False\n",
    "        if self.rank[u] > self.rank[v]:\n",
    "            u, v = v, u\n",
    "        self.parent[u] = v\n",
    "        if self.rank[u] == self.rank[v]:\n",
    "            self.rank[v] += 1\n",
    "        return True\n",
    "\n",
    "class Solution:\n",
    "    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n",
    "        alice = UnionFind(n)\n",
    "        bob = UnionFind(n)\n",
    "        cnt = 0  # Number of edges removed\n",
    "\n",
    "        # Step 2: Add type 3 edges to both Alice and Bob\n",
    "        for t, u, v in edges:\n",
    "            if t == 3:\n",
    "                if not alice.merge(u-1, v-1):\n",
    "                    cnt += 1\n",
    "                else:\n",
    "                    bob.merge(u-1, v-1)\n",
    "\n",
    "        # Step 3: Add type 1 and type 2 edges\n",
    "        for t, u, v in edges:\n",
    "            if t == 1 and not alice.merge(u-1, v-1):\n",
    "                cnt += 1\n",
    "            if t == 2 and not bob.merge(u-1, v-1):\n",
    "                cnt += 1\n",
    "\n",
    "        # Step 4: Check if Alice and Bob can traverse the graph completely\n",
    "        if len(set(alice.find(i) for i in range(n))) > 1 or len(set(bob.find(i) for i in range(n))) > 1:\n",
    "            return -1\n",
    "\n",
    "        return cnt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n",
    "        res = 0\n",
    "        uf_alice = UnionFind(n)\n",
    "        uf_bob = UnionFind(n)\n",
    "        for _type,n1,n2 in edges:\n",
    "            if _type == 3:\n",
    "                if not uf_alice.is_connected(n1,n2):\n",
    "                    uf_alice.merge(n1,n2)\n",
    "                    uf_bob.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "        for _type,n1,n2 in edges:\n",
    "            if _type == 1:\n",
    "                if not uf_alice.is_connected(n1,n2):\n",
    "                    uf_alice.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "            if _type == 2:\n",
    "                if not uf_bob.is_connected(n1,n2):\n",
    "                    uf_bob.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "\n",
    "        return -1 if uf_alice.num_of_sets * uf_bob.num_of_sets > 1 else res            \n",
    "\n",
    "class UnionFind:\n",
    "    def __init__(self,size):\n",
    "        self.father = [None] * (size+1)\n",
    "        self.num_of_sets = size\n",
    "    \n",
    "    def find(self,x):\n",
    "        if self.father[x] is None: return x\n",
    "        self.father[x] = self.find(self.father[x])\n",
    "        return self.father[x]\n",
    "    \n",
    "    def is_connected(self,x,y):\n",
    "        return self.find(x) == self.find(y)\n",
    "    \n",
    "    def merge(self,x,y):\n",
    "        self.father[self.find(x)] = self.find(y)\n",
    "        self.num_of_sets -= 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class UnionFind:\n",
    "    def __init__(self,size):\n",
    "        self.father = [None] * (size+1)\n",
    "        self.num_of_sets = size\n",
    "    \n",
    "    def find(self,x):\n",
    "        if self.father[x] is None: return x\n",
    "        self.father[x] = self.find(self.father[x])\n",
    "        return self.father[x]\n",
    "    \n",
    "    def is_connected(self,x,y):\n",
    "        return self.find(x) == self.find(y)\n",
    "    \n",
    "    def merge(self,x,y):\n",
    "        self.father[self.find(x)] = self.find(y)\n",
    "        self.num_of_sets -= 1\n",
    "\n",
    "class Solution:\n",
    "    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n",
    "        res = 0\n",
    "        uf_alice = UnionFind(n)\n",
    "        uf_bob = UnionFind(n)\n",
    "        for _type,n1,n2 in edges:\n",
    "            if _type == 3:\n",
    "                if not uf_alice.is_connected(n1,n2):\n",
    "                    uf_alice.merge(n1,n2)\n",
    "                    uf_bob.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "        for _type,n1,n2 in edges:\n",
    "            if _type == 1:\n",
    "                if not uf_alice.is_connected(n1,n2):\n",
    "                    uf_alice.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "            if _type == 2:\n",
    "                if not uf_bob.is_connected(n1,n2):\n",
    "                    uf_bob.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "\n",
    "        return -1 if uf_alice.num_of_sets * uf_bob.num_of_sets > 1 else res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class UnionFind:\n",
    "    def __init__(self,size):\n",
    "        self.father = [None] * (size+1)\n",
    "        self.num_of_sets = size\n",
    "    \n",
    "    def find(self,x):\n",
    "        if self.father[x] is None: return x\n",
    "        self.father[x] = self.find(self.father[x])\n",
    "        return self.father[x]\n",
    "    \n",
    "    def is_connected(self,x,y):\n",
    "        return self.find(x) == self.find(y)\n",
    "    \n",
    "    def merge(self,x,y):\n",
    "        self.father[self.find(x)] = self.find(y)\n",
    "        self.num_of_sets -= 1\n",
    "\n",
    "class Solution:\n",
    "    def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n",
    "        res = 0\n",
    "        \n",
    "        uf_alice = UnionFind(n)\n",
    "        uf_bob = UnionFind(n)\n",
    "\n",
    "        for _type,n1,n2 in edges:\n",
    "            #如果此边为共用边, 且alice目前边中n1,n2未连接, 加入此边\n",
    "            if _type == 3:\n",
    "                if not uf_alice.is_connected(n1,n2):\n",
    "                    uf_alice.merge(n1,n2)\n",
    "                    uf_bob.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "        \n",
    "        for _type,n1,n2 in edges:\n",
    "            if _type == 1:\n",
    "                if not uf_alice.is_connected(n1,n2):\n",
    "                    uf_alice.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "            \n",
    "            if _type == 2:\n",
    "                if not uf_bob.is_connected(n1,n2):\n",
    "                    uf_bob.merge(n1,n2)\n",
    "                else:\n",
    "                    res += 1\n",
    "\n",
    "        return -1 if uf_alice.num_of_sets * uf_bob.num_of_sets > 1 else res\n",
    "\n",
    "                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def reorderList(self, head: ListNode) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify head in-place instead.\n",
    "        \"\"\"\n",
    "        if not head:\n",
    "            return None\n",
    "        Merged_head = merge = ListNode(0)\n",
    "\n",
    "        slow = fast = head\n",
    "        while fast.next:\n",
    "            pNext = fast.next\n",
    "            if pNext.next:\n",
    "                slow = slow.next\n",
    "                fast = pNext.next\n",
    "            else:\n",
    "                break\n",
    "\n",
    "        temp = slow.next\n",
    "        back = self.reverseList(temp)\n",
    "        slow.next = None\n",
    "\n",
    "        i = 1\n",
    "        while head and back:\n",
    "            if i & 1 == 1:\n",
    "                merge.next = head\n",
    "                merge = merge.next\n",
    "                head = head.next\n",
    "            else:\n",
    "                merge.next = back\n",
    "                merge = merge.next\n",
    "                back = back.next\n",
    "            i += 1\n",
    "\n",
    "        if head:\n",
    "            merge.next = head\n",
    "        if back:\n",
    "            merge.next = back\n",
    "\n",
    "        return Merged_head.next\n",
    "\n",
    "    def reverseList(self, head):\n",
    "        if not head:\n",
    "            return None\n",
    "        preNode = None\n",
    "        pNode = head\n",
    "        while pNode:\n",
    "            pNext = pNode.next\n",
    "            pNode.next = preNode\n",
    "            preNode = pNode\n",
    "            pNode = pNext\n",
    "\n",
    "        return preNode"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "\"\"\"\n",
    "我觉得可以找到linked list的中心，然后把后半部分给revert了\n",
    "接下来重新merge\n",
    "\"\"\"\n",
    "\n",
    "class Solution:\n",
    "    def reorderList(self, head: ListNode) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify head in-place instead.\n",
    "        \"\"\"\n",
    "        if not head:\n",
    "            return head\n",
    "        # Find middle of the list\n",
    "        slow = head\n",
    "        fast = head\n",
    "        while fast.next and fast.next.next:\n",
    "            slow = slow.next\n",
    "            fast = fast.next.next\n",
    "        second_half_head = slow.next\n",
    "        slow.next = None\n",
    "        # rever second half\n",
    "        prev = None\n",
    "        while second_half_head:\n",
    "            nex = second_half_head.next\n",
    "            second_half_head.next = prev\n",
    "            prev = second_half_head\n",
    "            second_half_head = nex\n",
    "        second_half_head = prev\n",
    "        # merge\n",
    "        dummy = ListNode(-1)\n",
    "        curr = dummy\n",
    "        while head and second_half_head:\n",
    "            curr.next = head\n",
    "            head = head.next\n",
    "            curr.next.next = second_half_head\n",
    "            second_half_head = second_half_head.next\n",
    "            curr = curr.next.next\n",
    "        if head:\n",
    "            curr.next = head\n",
    "            head.next = None\n",
    "        return dummy.next\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reorderList(self, head: ListNode) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify head in-place instead.\n",
    "        \"\"\"\n",
    "        if head or head.next:\n",
    "            fast, slow = head, head\n",
    "            while fast.next and fast.next.next:\n",
    "                fast = fast.next.next\n",
    "                slow = slow.next\n",
    "            # middle point of the list\n",
    "            pnt1 = slow\n",
    "            # reverse the right half part of list\n",
    "            pnt1 = self.reverseList(pnt1)\n",
    "            self.mergeList(head, pnt1)\n",
    "    # reverse the list\n",
    "    def reverseList(self, head: ListNode) -> ListNode:\n",
    "        # 使用递归\n",
    "        # 这个列表长度小于等于1：\n",
    "        if head == None or head.next == None:\n",
    "            return head\n",
    "        # 列表长度大于1\n",
    "        new_head = self.reverseList(head.next)\n",
    "        # 从head.next开始，head.next的下一个为head,并且new_head到最后一个\n",
    "        head.next.next = head\n",
    "        # head.next为None, head变成tail\n",
    "        head.next = None\n",
    "        return new_head\n",
    "    # merge the 2 list in one by one manner\n",
    "    def mergeList(self, l1:ListNode, l2:ListNode):\n",
    "        while l1 and l2:\n",
    "            temp1, temp2 = l1.next, l2.next\n",
    "\n",
    "            l1.next = l2\n",
    "            l1 = temp1\n",
    "\n",
    "            l2.next = l1\n",
    "            l2 = temp2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reorderList(self, head: ListNode) -> None:\n",
    "        if not head:\n",
    "            return head\n",
    "        slow = fast = head\n",
    "        while fast and fast.next:\n",
    "            slow = slow.next\n",
    "            fast = fast.next.next\n",
    "        bp = slow\n",
    "        p = slow.next\n",
    "        slow.next = None\n",
    "        while p:\n",
    "            tmp = p.next\n",
    "            p.next = slow\n",
    "            slow = p\n",
    "            p = tmp\n",
    "        self.merge(head,slow,bp)\n",
    "    \n",
    "    def merge(self,x,y,gap):\n",
    "        if x == gap:\n",
    "            x.next = None\n",
    "            return\n",
    "        if not y:\n",
    "            return\n",
    "        xn = x.next\n",
    "        yn = y.next\n",
    "        x.next = y\n",
    "        y.next = xn\n",
    "        self.merge(xn,yn,gap)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def reorderList(self, head: Optional[ListNode]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify head in-place instead.\n",
    "        \"\"\"\n",
    "\n",
    "        ## 1. 找到中点n: 双指针\n",
    "        ## 2. 从第n位置开始反转链表\n",
    "        ## 3. 合并两个链表\n",
    "\n",
    "        def findMiddle(head):\n",
    "            slow, fast = head, head\n",
    "            while fast.next and fast.next.next:\n",
    "                slow = slow.next\n",
    "                fast = fast.next.next\n",
    "            return slow\n",
    "        \n",
    "        def reverseList(head):\n",
    "            if not head or not head.next:\n",
    "                return head\n",
    "            resNode = reverseList(head.next)\n",
    "            head.next.next = head\n",
    "            head.next = None\n",
    "            return resNode\n",
    "\n",
    "        def mergeList(l1, l2):\n",
    "            # 这段代码不对，原因是什么？\n",
    "            # phead = p = ListNode(0)\n",
    "            # while l1 and l2:\n",
    "            #     p.next = l1\n",
    "            #     p = p.next\n",
    "            #     p.next = l2\n",
    "            #     p = p.next\n",
    "            #     l1 = l1.next  \n",
    "            #     l2 = l2.next\n",
    "            # p.next = l1 if l1 else l2\n",
    "            # return phead.next\n",
    "\n",
    "            while l1 and l2:\n",
    "                l1_tmp = l1.next\n",
    "                l2_tmp = l2.next\n",
    "                l1.next = l2\n",
    "                l1 = l1_tmp\n",
    "                l2.next = l1\n",
    "                l2 = l2_tmp\n",
    "\n",
    "        \n",
    "        if not head or not head.next:\n",
    "            return head\n",
    "        mid_node = findMiddle(head)\n",
    "        l1, l2 = head, mid_node.next\n",
    "        mid_node.next = None\n",
    "        l2 = reverseList(l2)\n",
    "        res = mergeList(l1, l2)\n",
    "        return res\n",
    "            \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "\n",
    "class Solution:\n",
    "    def Reverse(self,head):\n",
    "        if head is None or head.next is None:\n",
    "            return head\n",
    "        p = self.Reverse(head.next)\n",
    "        head.next.next = head\n",
    "        head.next = None\n",
    "        return p\n",
    "    def findMid(self,head):\n",
    "        slow = fast = head\n",
    "        while fast is not None and fast.next is not None:\n",
    "            slow = slow.next\n",
    "            fast = fast.next.next\n",
    "        return slow\n",
    "    def mergeList(self,headA,headB):\n",
    "        pointA = headA\n",
    "        pointB = headB\n",
    "        while pointA and pointB:\n",
    "            tmp_nodeA = pointA.next\n",
    "            tmp_nodeB = pointB.next\n",
    "            pointA.next = pointB\n",
    "            pointA = tmp_nodeA\n",
    "            pointB.next = pointA\n",
    "            pointB = tmp_nodeB\n",
    "    def reorderList(self, head: Optional[ListNode]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify head in-place instead.\n",
    "        \"\"\"\n",
    "        if head is None:\n",
    "            return head\n",
    "        midhead = self.findMid(head)\n",
    "        l1 = head\n",
    "        l2 = self.Reverse(midhead.next)\n",
    "        # print(l2.next)\n",
    "        midhead.next = None\n",
    "        self.mergeList(l1,l2)\n",
    "        # return head\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def sortList(self, head):\n",
    "        \"\"\"\n",
    "        :type head: ListNode\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        if (not head) or (not head.next):\n",
    "            return head\n",
    "        \n",
    "        fast,slow,prev=head,head,head\n",
    "        \n",
    "        while fast and fast.next:\n",
    "            prev=slow\n",
    "            fast=fast.next.next\n",
    "            slow=slow.next\n",
    "            \n",
    "        prev.next=None\n",
    "        \n",
    "        return self.merge(self.sortList(head),self.sortList(slow))\n",
    "        \n",
    "    def merge(self,l1,l2):\n",
    "        head=ListNode(0)\n",
    "        pre=head\n",
    "        \n",
    "        while l1 and l2:\n",
    "            if l1.val<l2.val:\n",
    "                pre.next=l1\n",
    "                l1,pre=l1.next,pre.next\n",
    "            else:\n",
    "                pre.next=l2\n",
    "                l2,pre=l2.next,pre.next\n",
    "                \n",
    "        if l1:\n",
    "            pre.next=l1\n",
    "        if l2:\n",
    "            pre.next=l2\n",
    "            \n",
    "        return head.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def sortList(self, head):\n",
    "        \"\"\"\n",
    "        :type head: ListNode\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        def mergeSort(prev, merge_size):\n",
    "            l = prev.next\n",
    "            msize = merge_size // 2\n",
    "            r = l\n",
    "            while msize:\n",
    "                r = r.next\n",
    "                if r == None:\n",
    "                    break\n",
    "                msize -= 1\n",
    "            # it's the last segment\n",
    "            if r == None:\n",
    "                return None\n",
    "            \n",
    "            l_size = r_size = merge_size // 2\n",
    "            while l_size > 0 and r_size > 0 and r:\n",
    "                if l.val < r.val:\n",
    "                    prev.next, l = l, l.next\n",
    "                    l_size -= 1\n",
    "                else:\n",
    "                    prev.next, r = r, r.next\n",
    "                    r_size -= 1\n",
    "                prev = prev.next\n",
    "            \n",
    "            while l_size > 0:\n",
    "                prev.next, l = l, l.next\n",
    "                prev = prev.next\n",
    "                l_size -= 1\n",
    "                \n",
    "            while r_size > 0 and r:\n",
    "                prev.next, r = r, r.next\n",
    "                prev = prev.next\n",
    "                r_size -= 1\n",
    "\n",
    "            # it's important\n",
    "            prev.next = r\n",
    "                \n",
    "            # it's the last segment\n",
    "            if r_size and not r:\n",
    "                return None\n",
    "            return prev\n",
    "        \n",
    "        size = 0\n",
    "        node = head\n",
    "        while node:\n",
    "            node = node.next\n",
    "            size += 1\n",
    "        \n",
    "        new_head = ListNode(-1)\n",
    "        prev = new_head\n",
    "        prev.next = head\n",
    "        merge_size = 2\n",
    "        while merge_size < size * 2:\n",
    "            while prev and prev.next:\n",
    "                prev = mergeSort(prev, merge_size)\n",
    "            merge_size *= 2\n",
    "            prev = new_head\n",
    "\n",
    "        return new_head.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def sortList(self, head):\n",
    "        \"\"\"\n",
    "        :type head: ListNode\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        if head is None or head.next is None:\n",
    "            return head\n",
    "        mid = self.get_mid(head)\n",
    "        l = head\n",
    "        r = mid.next\n",
    "        print(l.val)\n",
    "        \n",
    "        mid.next = None\n",
    "        print(r.val)\n",
    "        return self.merge(self.sortList(l), self.sortList(r))\n",
    "\n",
    "    def merge(self, p, q):\n",
    "            tmp = ListNode(0)\n",
    "            h = tmp\n",
    "            while p and q:\n",
    "                if p.val < q.val:\n",
    "                    h.next = p\n",
    "                    p = p.next\n",
    "                else:\n",
    "                    h.next = q\n",
    "                    q = q.next\n",
    "                h = h.next\n",
    "            if p:\n",
    "                h.next = p\n",
    "            if q:\n",
    "                h.next = q\n",
    "            return tmp.next\n",
    "\n",
    "    def get_mid(self, node):\n",
    "        if node is None:\n",
    "            return node\n",
    "        fast = slow = node\n",
    "        while fast.next and fast.next.next:\n",
    "            slow = slow.next\n",
    "            fast = fast.next.next\n",
    "        return slow"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def sortList(self, head):\n",
    "        \"\"\"\n",
    "        :type head: ListNode\n",
    "        :rtype: ListNode\n",
    "        \"\"\"\n",
    "        if head is None or head.next is None:\n",
    "            return head\n",
    "        slow = fast = head\n",
    "        while fast and fast.next:\n",
    "            pre = slow\n",
    "            slow = slow.next\n",
    "            fast = fast.next.next\n",
    "        pre.next = None\n",
    "        return self.mergeTwoLists(self.sortList(head), self.sortList(slow))\n",
    "    \n",
    "    def mergeTwoLists(self, l1, l2):\n",
    "        dummy_l0 = ListNode(0)\n",
    "        curr = dummy_l0\n",
    "        while l1 and l2:\n",
    "            if l1.val <= l2.val:\n",
    "                curr.next = ListNode(l1.val)\n",
    "                curr = curr.next\n",
    "                l1 = l1.next\n",
    "            else:\n",
    "                curr.next = ListNode(l2.val)\n",
    "                curr = curr.next\n",
    "                l2 = l2.next\n",
    "        if l2:\n",
    "            curr.next = l2\n",
    "        else:\n",
    "            curr.next = l1\n",
    "        return dummy_l0.next\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def sortList(self, head: ListNode) -> ListNode:\n",
    "        if not head or not head.next: \n",
    "            return head\n",
    "        slow = head\n",
    "        fast = head\n",
    "        # 用快慢指针分成两部分\n",
    "        while fast.next and fast.next.next:\n",
    "            slow = slow.next\n",
    "            fast = fast.next.next\n",
    "        # 找到左右部分, 把左部分最后置空\n",
    "        mid = slow.next\n",
    "        slow.next = None\n",
    "        # 递归下去\n",
    "        left = self.sortList(head)\n",
    "        right = self.sortList(mid)\n",
    "        # 合并\n",
    "        return self.merge(left, right)\n",
    "\n",
    "    def merge(self, left, right):\n",
    "        dummy = ListNode(0)\n",
    "        p = dummy\n",
    "        l = left\n",
    "        r = right\n",
    "\n",
    "        while l and r:\n",
    "            if l.val < r.val:\n",
    "                p.next = l\n",
    "                l = l.next\n",
    "                p = p.next\n",
    "            else:\n",
    "                p.next = r\n",
    "                r = r.next\n",
    "                p = p.next\n",
    "        if l:\n",
    "            p.next = l\n",
    "        if r:\n",
    "            p.next = r\n",
    "        return dummy.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "class ListNode:\n",
    "    def __init__(self, val=0, next=None):\n",
    "        self.val = val\n",
    "        self.next = next\n",
    "\n",
    "    def traverse(self):\n",
    "        p = self\n",
    "        while p:\n",
    "            print(p.val)\n",
    "            p = p.next\n",
    "\n",
    "\n",
    "class LinkedList:\n",
    "    def __init__(self):\n",
    "        self.head = None\n",
    "\n",
    "    def from_list(self, nums: list):\n",
    "        p = self.head = None\n",
    "        for n in nums:\n",
    "            if not self.head:\n",
    "                self.head = p = ListNode(n)\n",
    "            else:\n",
    "                p.next = ListNode(n)\n",
    "                p = p.next\n",
    "\n",
    "    def traverse(self):\n",
    "        p = self.head\n",
    "        while p:\n",
    "            print(p.val)\n",
    "            p = p.next\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def sortList(self, head: ListNode) -> ListNode:\n",
    "\n",
    "        def merge_sort(head, length):\n",
    "            if length <= 1:\n",
    "                return head\n",
    "            m = length // 2\n",
    "            prev_p, p = None, head\n",
    "            for _ in range(m):\n",
    "                prev_p, p = p, p.next\n",
    "            prev_p.next = None\n",
    "\n",
    "            h1 = merge_sort(head, m)\n",
    "            h2 = merge_sort(p, length - m)\n",
    "            h3 = merge(h1, h2)\n",
    "            return h3\n",
    "\n",
    "        def merge(h1, h2):\n",
    "            h3 = p = ListNode()\n",
    "            while h1 and h2:\n",
    "                if h1.val < h2.val:\n",
    "                    p.next = h1\n",
    "                    h1 = h1.next\n",
    "                else:\n",
    "                    p.next = h2\n",
    "                    h2 = h2.next\n",
    "                p = p.next\n",
    "            if h1:\n",
    "                p.next = h1\n",
    "            if h2:\n",
    "                p.next = h2\n",
    "            return h3.next\n",
    "\n",
    "        length, p = 0, head\n",
    "        while p:\n",
    "            length += 1\n",
    "            p = p.next\n",
    "        return merge_sort(head, length)\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, x):\n",
    "#         self.val = x\n",
    "#         self.next = None\n",
    "\n",
    "class Solution:\n",
    "    def sortList(self, head: ListNode) -> ListNode:\n",
    "        if not head or not head.next:\n",
    "            return head\n",
    "        slow = head\n",
    "        fast = head.next\n",
    "        while fast and fast.next:\n",
    "            slow = slow.next\n",
    "            fast = fast.next.next\n",
    "        mid = slow.next\n",
    "        slow.next = None\n",
    "        left = self.sortList(head)\n",
    "        right = self.sortList(mid)\n",
    "        return self.merge(left,right)\n",
    "    def merge(self,l1,l2):\n",
    "        p = ListNode(0)\n",
    "        q = p\n",
    "        while l1 and l2:\n",
    "            if l1.val<l2.val:\n",
    "                p.next = ListNode(l1.val)\n",
    "                l1 = l1.next\n",
    "            else:\n",
    "                p.next = ListNode(l2.val)\n",
    "                l2 = l2.next\n",
    "            p = p.next\n",
    "        p.next = l1 or l2\n",
    "        return q.next\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: ListNode) -> ListNode:\n",
    "        def merge_sort(left, right):\n",
    "            if left == right: return left\n",
    "            mid = get_mid(left, right)\n",
    "            mid_next = mid.next\n",
    "            mid.next = None\n",
    "            return merge(merge_sort(left, mid), merge_sort(mid_next, right))\n",
    "        \n",
    "        def merge(left, right):\n",
    "            head = ListNode(0)\n",
    "            head_ = head\n",
    "            while left and right:\n",
    "            # 2->4->1->3\n",
    "                if left.val > right.val:\n",
    "                    head.next = ListNode(right.val)\n",
    "                    right = right.next\n",
    "                else:\n",
    "                    head.next = ListNode(left.val)\n",
    "                    left = left.next\n",
    "                head = head.next\n",
    "\n",
    "            if left:\n",
    "                head.next = left\n",
    "            if right:\n",
    "                head.next = right\n",
    "\n",
    "            return head_.next\n",
    "        \n",
    "        def get_mid(left,right):\n",
    "            mid = left\n",
    "            counter = 0\n",
    "            while left!=right:\n",
    "                left = left.next\n",
    "                counter += 1\n",
    "            counter //= 2\n",
    "            while counter:\n",
    "                mid = mid.next\n",
    "                counter -=1\n",
    "            return mid\n",
    "\n",
    "        if head is None: return None\n",
    "        left = head\n",
    "        while head.next:\n",
    "            head = head.next\n",
    "        return merge_sort(left, head)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: ListNode) -> ListNode:\n",
    "        if not head or not head.next:\n",
    "            return head\n",
    "        \n",
    "        tail = self.get_tail(head)\n",
    "        return self.helper(head, tail)\n",
    "\n",
    "    \n",
    "    def helper(self, head, tail):\n",
    "        if head == tail:\n",
    "            return ListNode(head.val)\n",
    "\n",
    "        mid = self.get_mid(head, tail)\n",
    "        left = self.helper(head, mid)\n",
    "        right = self.helper(mid.next, tail)\n",
    "\n",
    "        return self.merge(left, right)\n",
    "\n",
    "    \n",
    "    def merge(self, left, right):\n",
    "        dummy = curt = ListNode(None)\n",
    "\n",
    "        while left and right:\n",
    "            if left.val < right.val:\n",
    "                curt.next = left\n",
    "                left = left.next\n",
    "            else:\n",
    "                curt.next = right\n",
    "                right = right.next\n",
    "            curt = curt.next\n",
    "\n",
    "        if left:\n",
    "            curt.next = left\n",
    "        else:\n",
    "            curt.next = right\n",
    "\n",
    "        return dummy.next\n",
    "\n",
    "    \n",
    "    def get_mid(self, head, tail):\n",
    "        slow = head\n",
    "        fast = head.next\n",
    "        while fast != tail and fast.next != tail:\n",
    "            slow = slow.next\n",
    "            fast = fast.next.next\n",
    "        return slow\n",
    "\n",
    "\n",
    "    def get_tail(self, head):\n",
    "        while head.next:\n",
    "            head = head.next\n",
    "        return head"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: ListNode) -> ListNode:\n",
    "        def sortFunc(head: ListNode, tail: ListNode) -> ListNode:\n",
    "            if not head:\n",
    "                return head\n",
    "            if head.next == tail:\n",
    "                head.next = None\n",
    "                return head\n",
    "            slow = fast = head\n",
    "            while fast != tail:\n",
    "                slow = slow.next\n",
    "                fast = fast.next\n",
    "                if fast != tail:\n",
    "                    fast = fast.next\n",
    "            mid = slow\n",
    "            return merge(sortFunc(head, mid), sortFunc(mid, tail))\n",
    "            \n",
    "        def merge(head1: ListNode, head2: ListNode) -> ListNode:\n",
    "            dummyHead = ListNode(0)\n",
    "            temp, temp1, temp2 = dummyHead, head1, head2\n",
    "            while temp1 and temp2:\n",
    "                if temp1.val <= temp2.val:\n",
    "                    temp.next = temp1\n",
    "                    temp1 = temp1.next\n",
    "                else:\n",
    "                    temp.next = temp2\n",
    "                    temp2 = temp2.next\n",
    "                temp = temp.next\n",
    "            if temp1:\n",
    "                temp.next = temp1\n",
    "            elif temp2:\n",
    "                temp.next = temp2\n",
    "            return dummyHead.next\n",
    "        \n",
    "        return sortFunc(head, None)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        if not head or not head.next: return head # termination.\n",
    "        # cut the LinkedList at the mid index.\n",
    "        slow, fast = head, head.next\n",
    "        while fast and fast.next:\n",
    "            fast, slow = fast.next.next, slow.next\n",
    "        mid, slow.next = slow.next, None # save and cut.\n",
    "        # recursive for cutting.\n",
    "        left, right = self.sortList(head), self.sortList(mid)\n",
    "        # merge `left` and `right` linked list and return it.\n",
    "        h = res = ListNode(0)\n",
    "        while left and right:\n",
    "            if left.val < right.val: h.next, left = left, left.next\n",
    "            else: h.next, right = right, right.next\n",
    "            h = h.next\n",
    "        h.next = left if left else right\n",
    "        return res.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        def binary(node,tail):\n",
    "            if not node:\n",
    "                return None\n",
    "            if node.next==tail:\n",
    "                node.next=None\n",
    "                return node\n",
    "            slow,fast=node,node\n",
    "            while fast!=tail:\n",
    "                fast=fast.next\n",
    "                slow=slow.next\n",
    "                if fast!=tail:\n",
    "                    # print('node',node,'tail',tail)\n",
    "                    fast=fast.next\n",
    "            mid=slow\n",
    "            return merge(binary(node,mid),binary(mid,tail))\n",
    "        def merge(node1,node2):\n",
    "            # print(node1,node2)\n",
    "            node=ListNode(-1)\n",
    "            temp,a,b=node,node1,node2\n",
    "            while a and b:\n",
    "                # print('in',a,b)\n",
    "                if a.val>=b.val:\n",
    "                    # print('in')\n",
    "                    temp.next=b\n",
    "                    # print('tem',temp)\n",
    "                    temp=temp.next\n",
    "                    b=b.next\n",
    "                else:\n",
    "                    temp.next=a\n",
    "                    temp=temp.next\n",
    "                    a=a.next\n",
    "            if a:\n",
    "                temp.next=a\n",
    "            if b:\n",
    "                temp.next=b\n",
    "            # print(node.next,temp)\n",
    "            return node.next\n",
    "\n",
    "        return binary(head,None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "\"\"\"\n",
    "1. 找到链表的中点，以中点为分界，将链表拆分成两个子链表。寻找链表的中点可以使用快慢指针的做法，快指针每次移动 22 步，慢指针每次移动 11 步，当快指针到达链表末尾时，慢指针指向的链表节点即为链表的中点。\n",
    "2. 对两个子链表分别排序。\n",
    "3. 将两个排序后的子链表合并，得到完整的排序后的链表。可以使用「21. 合并两个有序链表」的做法，将两个有序的子链表进行合并。\n",
    "\"\"\"\n",
    "class Solution:\n",
    "    def sortList(self, head: ListNode) -> ListNode:\n",
    "        def sortFunc(head: ListNode, tail: ListNode) -> ListNode:\n",
    "            if not head:\n",
    "                return head\n",
    "            if head.next == tail:\n",
    "                head.next = None\n",
    "                return head\n",
    "            slow = fast = head\n",
    "            while fast != tail:\n",
    "                slow = slow.next\n",
    "                fast = fast.next\n",
    "                if fast != tail:\n",
    "                    fast = fast.next\n",
    "            mid = slow\n",
    "            return merge(sortFunc(head, mid), sortFunc(mid, tail))\n",
    "            \n",
    "        def merge(head1: ListNode, head2: ListNode) -> ListNode:\n",
    "            dummyHead = ListNode(0)\n",
    "            t, t1, t2 = dummyHead, head1, head2\n",
    "            while t1 and t2:\n",
    "                if t1.val < t2.val:\n",
    "                    t.next = t1\n",
    "                    t = t1\n",
    "                    t1 = t1.next\n",
    "                else:\n",
    "                    t.next = t2\n",
    "                    t = t2\n",
    "                    t2 = t2.next\n",
    "            if t1:\n",
    "                t.next = t1\n",
    "            if t2:\n",
    "                t.next = t2\n",
    "            return dummyHead.next\n",
    "\n",
    "        return sortFunc(head, None)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        if head is None:\n",
    "            return head\n",
    "        node_list = []\n",
    "        while head:\n",
    "            node_list.append(head)\n",
    "            head = head.next\n",
    "        def merge_sort(node_list):\n",
    "            n = len(node_list)\n",
    "            if n<2:\n",
    "                return node_list\n",
    "            p = n//2\n",
    "            res = []\n",
    "            left_sort = merge_sort(node_list[:p])\n",
    "            right_sort = merge_sort(node_list[p:])\n",
    "            l = 0\n",
    "            r = 0\n",
    "            while l<len(left_sort) and r<len(right_sort):\n",
    "                if left_sort[l].val<right_sort[r].val:\n",
    "                    res.append(left_sort[l])\n",
    "                    l+=1\n",
    "                else:\n",
    "                    res.append(right_sort[r])\n",
    "                    r+=1\n",
    "            if l<len(left_sort):\n",
    "                res = res + left_sort[l:]\n",
    "            elif r<len(right_sort):\n",
    "                res = res + right_sort[r:]\n",
    "            return res\n",
    "        res = merge_sort(node_list)\n",
    "        prev = ListNode(0)\n",
    "        node = prev\n",
    "        for i in range(len(res)):\n",
    "            node.next = res[i]\n",
    "            node = res[i]\n",
    "        node.next = None\n",
    "        return prev.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def merge(self,left,right):\n",
    "        head = temListNode = ListNode(0)\n",
    "        while left and right:\n",
    "            if left.val < right.val:\n",
    "                temListNode.next,left = left,left.next\n",
    "            else:\n",
    "                temListNode.next,right = right,right.next\n",
    "            temListNode = temListNode.next\n",
    "        temListNode.next = left if left else right\n",
    "        return head.next\n",
    "\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        if not head or not head.next:return head\n",
    "        slow,fast = head,head.next\n",
    "        while fast and fast.next:\n",
    "            slow = slow.next\n",
    "            fast = fast.next.next\n",
    "        mid,slow.next = slow.next,None\n",
    "        res = self.merge(self.sortList(head),self.sortList(mid))\n",
    "\n",
    "        return res\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        p = head\n",
    "        l = 0\n",
    "        while p:\n",
    "            p = p.next\n",
    "            l += 1\n",
    "        curlen = 1\n",
    "        dummy = ListNode(0, head)\n",
    "        while curlen < l:\n",
    "            cur = dummy.next\n",
    "            p = dummy\n",
    "            while cur:\n",
    "                left = cur\n",
    "                right = self.cut(curlen, cur)\n",
    "                cur = self.cut(curlen, right)\n",
    "                p.next = self.merge(left, right)\n",
    "                while p.next:\n",
    "                    p = p.next\n",
    "            curlen <<= 1\n",
    "\n",
    "        return dummy.next\n",
    "        \n",
    "            \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "    def cut(self, length, node):\n",
    "        for i in range(length - 1):\n",
    "            if node:\n",
    "                node = node.next\n",
    "            else:\n",
    "                return None\n",
    "        if not node:\n",
    "            return None\n",
    "        ret = node.next\n",
    "        node.next = None\n",
    "        return ret\n",
    "\n",
    "    def merge(self, l1, l2):\n",
    "        dummy = ListNode(0)\n",
    "        p = dummy\n",
    "        while l1 and l2:\n",
    "            if l1.val > l2.val:\n",
    "                p.next = l2\n",
    "                l2 = l2.next\n",
    "            else:\n",
    "                p.next = l1\n",
    "                l1 = l1.next\n",
    "            p = p.next\n",
    "        if l1:\n",
    "            p.next = l1\n",
    "        if l2:\n",
    "            p.next = l2\n",
    "        return dummy.next\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        if head:\n",
    "            if head.next is None:\n",
    "                return head\n",
    "            length = 0\n",
    "            cur = head\n",
    "            while cur:\n",
    "                length += 1\n",
    "                cur = cur.next\n",
    "            sublength = 1\n",
    "            cur_head = head\n",
    "            while sublength <= length:\n",
    "                res_head = res_tail = ListNode(None)\n",
    "                head1 = cur_head\n",
    "                while head1:\n",
    "                    head2 = self.get_firstN(head1, sublength)\n",
    "                    new_head1 = self.get_firstN(head2, sublength)\n",
    "                    head3, tail3 = self.merge(head1, head2)\n",
    "                    res_tail.next, res_tail = head3, tail3\n",
    "                    head1 = new_head1\n",
    "                cur_head = res_head.next\n",
    "                sublength = sublength * 2\n",
    "            return cur_head\n",
    "\n",
    "    def get_firstN(self, head, n):\n",
    "        cur = head\n",
    "        cnt = 0\n",
    "        next_head = None\n",
    "        while cur and cnt < n:\n",
    "            cnt += 1\n",
    "            if cnt == n:\n",
    "                tail, next_head = cur, cur.next\n",
    "                tail.next = None\n",
    "            else:\n",
    "                cur = cur.next\n",
    "        return next_head\n",
    "\n",
    "    def get_tail(self, head):\n",
    "        cur = tail = head\n",
    "        while cur:\n",
    "            tail, cur = cur, cur.next\n",
    "        return tail\n",
    "\n",
    "    def merge(self, list1, list2):\n",
    "        head = tail = ListNode(None)\n",
    "        cur1, cur2 = list1, list2\n",
    "        while cur1 and cur2:\n",
    "            if cur1.val <= cur2.val:\n",
    "                tail.next, cur1, tail = cur1, cur1.next, cur1\n",
    "            else:\n",
    "                tail.next, cur2, tail = cur2, cur2.next, cur2\n",
    "\n",
    "        tail.next = cur1 if cur1 else cur2\n",
    "        tail = self.get_tail(cur1 if cur1 else cur2)\n",
    "\n",
    "        return head.next, tail"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "\n",
    "        # 将整个链表一分为2，进行merge_sort，最后进行merge\n",
    "\n",
    "        if not head or not head.next:\n",
    "            return head\n",
    "\n",
    "        fastPoint = slowPoint = head\n",
    "        while fastPoint and fastPoint.next and  fastPoint.next.next:\n",
    "            fastPoint = fastPoint.next.next\n",
    "            slowPoint = slowPoint.next\n",
    "        rightHead = slowPoint.next\n",
    "        slowPoint.next = None\n",
    "\n",
    "        left = self.sortList(head)\n",
    "        right = self.sortList(rightHead)\n",
    "        return self.merge(left, right)\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "    def merge(self, left, right):\n",
    "        dumy = ListNode(0)\n",
    "        p = dumy\n",
    "        while left and right:\n",
    "            if left.val <= right.val:\n",
    "                p.next = left\n",
    "                left = left.next\n",
    "            else:\n",
    "                p.next = right\n",
    "                right = right.next\n",
    "            p = p.next\n",
    "        if left:\n",
    "            p.next = left\n",
    "        if right:\n",
    "            p.next = right\n",
    "        return dumy.next\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        def sort(head, tail):\n",
    "            if not head:\n",
    "                return head\n",
    "            if head.next == tail:\n",
    "                head.next = None\n",
    "                return head\n",
    "            slow = fast = head\n",
    "            while fast != tail:\n",
    "                slow = slow.next\n",
    "                fast = fast.next\n",
    "                if fast != tail:\n",
    "                    fast = fast.next\n",
    "            return self.merge(sort(head, slow), sort(slow, tail))\n",
    "        return sort(head, None)\n",
    "\n",
    "    def merge(self, list1, list2):\n",
    "        prehead = ListNode(-1)\n",
    "        cur = prehead\n",
    "        while list1 and list2:\n",
    "            if list1.val < list2.val:\n",
    "                cur.next = list1\n",
    "                list1 = list1.next\n",
    "            else:\n",
    "                cur.next = list2\n",
    "                list2 = list2.next\n",
    "        \n",
    "            cur = cur.next\n",
    "        cur.next = list1 if list1 else list2\n",
    "        return prehead.next"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "    # def __init__(self,val = 0,next = None):\n",
    "    #     self.val = val\n",
    "    #     self.next = next\n",
    "        \n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        def FindMid(head,tail):\n",
    "            if head is None:\n",
    "                return head\n",
    "            if head.next == tail:\n",
    "                head.next = None\n",
    "                return head\n",
    "            slow = fast = head\n",
    "            \n",
    "            while fast != tail:\n",
    "                slow = slow.next \n",
    "                fast = fast.next\n",
    "                if fast!= tail:\n",
    "                    fast = fast.next \n",
    "            mid = slow\n",
    "            \n",
    "            return merge(FindMid(head,mid),FindMid(mid,tail))\n",
    "        \n",
    "        def merge(list1,list2):\n",
    "            dummy = ListNode(0)\n",
    "            p = dummy\n",
    "            l1 = list1\n",
    "            l2 = list2\n",
    "            \n",
    "            while l1 and l2:\n",
    "                if l1.val <= l2.val:\n",
    "                    p.next = l1\n",
    "                    p = p.next\n",
    "                    l1 = l1.next\n",
    "                    \n",
    "                else:\n",
    "                    p.next = l2\n",
    "                    p = p.next \n",
    "                    l2 = l2.next \n",
    "                    \n",
    "                if l1:\n",
    "                    p.next = l1\n",
    "                if l2:\n",
    "                    p.next = l2\n",
    "                    \n",
    "            return dummy.next\n",
    "        return FindMid(head,None)\n",
    "                    \n",
    "         \n",
    "        \n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n",
    "        if head is None:\n",
    "            return None\n",
    "        cur = head\n",
    "        nums = []\n",
    "        while cur:\n",
    "            nums.append(cur.val)\n",
    "            cur = cur.next\n",
    "        nums = self.mergesort(nums)\n",
    "\n",
    "        dummy = ListNode(None)\n",
    "        dummy.next = head\n",
    "        i = 0\n",
    "        while head:\n",
    "            head.val = nums[i]\n",
    "            head=  head.next\n",
    "            i = i + 1\n",
    "\n",
    "        return dummy.next\n",
    "\n",
    "        \n",
    "\n",
    "    def merge(self, nums1, nums2):\n",
    "        nums = []\n",
    "        i = 0\n",
    "        j = 0\n",
    "        while i < len(nums1) and j < len(nums2):\n",
    "            if nums1[i] < nums2[j]:\n",
    "                nums.append(nums1[i])\n",
    "                i = i + 1\n",
    "            else:\n",
    "                nums.append(nums2[j])\n",
    "                j = j + 1\n",
    "        if i == len(nums1) :\n",
    "            nums = nums + nums2[j:]\n",
    "        if j == len(nums2):\n",
    "            nums = nums + nums1[i:]\n",
    "        return nums\n",
    "\n",
    "    def mergesort(self, nums):\n",
    "        if len(nums) <= 1:\n",
    "            return nums\n",
    "\n",
    "        mid = len(nums)//2\n",
    "        left_nums = self.mergesort(nums[:mid])\n",
    "        right_nums = self.mergesort(nums[mid:])\n",
    "        res = self.merge(left_nums, right_nums)\n",
    "        return res\n",
    "    \n",
    "        \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: \n",
    "        #方法1 遍历一边生成一个list，然后再生成一个新的链表\n",
    "        # preHead = ListNode(0)\n",
    "        # newList = preHead\n",
    "\n",
    "        # temp = []\n",
    "        # while head:\n",
    "        #     temp.append(head.val)\n",
    "        #     head = head.next\n",
    "        # temp.sort()\n",
    "  \n",
    "        # for i in range(len(temp)):\n",
    "        #     newList.next = ListNode(temp[i])\n",
    "        #     newList = newList.next\n",
    "        \n",
    "        # return preHead.next\n",
    "        \n",
    "        preHead = ListNode(0)\n",
    "        values = list()\n",
    "\n",
    "        while head:\n",
    "            values.append(head.val)\n",
    "            head = head.next\n",
    "        \n",
    "        values.sort()\n",
    "\n",
    "        pre = preHead\n",
    "        \n",
    "        for i in range(len(values)):\n",
    "            pre.next = ListNode(values[i])\n",
    "            pre = pre.next\n",
    "        \n",
    "        return preHead.next\n",
    "\n",
    "\n",
    "\n",
    "        # def sortFunc(head: ListNode, tail: ListNode) -> ListNode:\n",
    "        #     if not head:\n",
    "        #         return head\n",
    "        #     if head.next == tail:\n",
    "        #         head.next = None\n",
    "        #         return head\n",
    "        #     slow = fast = head\n",
    "        #     # slow 会过半\n",
    "        #     while fast != tail:\n",
    "        #         slow = slow.next\n",
    "        #         fast = fast.next\n",
    "        #         if fast != tail:\n",
    "        #             fast = fast.next\n",
    "        #     mid = slow\n",
    "        #     return merge(sortFunc(head, mid), sortFunc(mid, tail))\n",
    "\n",
    "        # def merge(head1: ListNode, head2: ListNode) -> ListNode:\n",
    "        #     preHead = ListNode(0)\n",
    "        #     temp, temp1, temp2 = preHead, head1, head2\n",
    "        #     while temp1 and temp2:\n",
    "        #         if temp1.val <= temp2.val:\n",
    "        #             temp.next = temp1\n",
    "        #             temp1 = temp1.next\n",
    "        #         else:\n",
    "        #             temp.next = temp2\n",
    "        #             temp2 = temp2.next\n",
    "        #         temp = temp.next\n",
    "        #     if temp1:\n",
    "        #         temp.next = temp1\n",
    "        #     elif temp2:\n",
    "        #         temp.next = temp2\n",
    "        #     return preHead.next\n",
    "        \n",
    "        return sortFunc(head, None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Definition for singly-linked list.\n",
    "# class ListNode:\n",
    "#     def __init__(self, val=0, next=None):\n",
    "#         self.val = val\n",
    "#         self.next = next\n",
    "class Solution:\n",
    "    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: \n",
    "        #方法1 遍历一边生成一个list，然后再生成一个新的链表\n",
    "        # preHead = ListNode(0)\n",
    "        # newList = preHead\n",
    "\n",
    "        # temp = []\n",
    "        # while head:\n",
    "        #     temp.append(head.val)\n",
    "        #     head = head.next\n",
    "        # temp.sort()\n",
    "  \n",
    "        # for i in range(len(temp)):\n",
    "        #     newList.next = ListNode(temp[i])\n",
    "        #     newList = newList.next\n",
    "        \n",
    "        # return preHead.next\n",
    "        \n",
    "        preHead = ListNode(0)\n",
    "        values = list()\n",
    "\n",
    "        while head:\n",
    "            values.append(head.val)\n",
    "            head = head.next\n",
    "        \n",
    "        values.sort()\n",
    "\n",
    "        pre = preHead\n",
    "        \n",
    "        for i in range(len(values)):\n",
    "            pre.next = ListNode(values[i])\n",
    "            pre = pre.next\n",
    "        \n",
    "        return preHead.next\n",
    "\n",
    "\n",
    "\n",
    "        # def sortFunc(head: ListNode, tail: ListNode) -> ListNode:\n",
    "        #     if not head:\n",
    "        #         return head\n",
    "        #     if head.next == tail:\n",
    "        #         head.next = None\n",
    "        #         return head\n",
    "        #     slow = fast = head\n",
    "        #     # slow 会过半\n",
    "        #     while fast != tail:\n",
    "        #         slow = slow.next\n",
    "        #         fast = fast.next\n",
    "        #         if fast != tail:\n",
    "        #             fast = fast.next\n",
    "        #     mid = slow\n",
    "        #     return merge(sortFunc(head, mid), sortFunc(mid, tail))\n",
    "\n",
    "        # def merge(head1: ListNode, head2: ListNode) -> ListNode:\n",
    "        #     preHead = ListNode(0)\n",
    "        #     temp, temp1, temp2 = preHead, head1, head2\n",
    "        #     while temp1 and temp2:\n",
    "        #         if temp1.val <= temp2.val:\n",
    "        #             temp.next = temp1\n",
    "        #             temp1 = temp1.next\n",
    "        #         else:\n",
    "        #             temp.next = temp2\n",
    "        #             temp2 = temp2.next\n",
    "        #         temp = temp.next\n",
    "        #     if temp1:\n",
    "        #         temp.next = temp1\n",
    "        #     elif temp2:\n",
    "        #         temp.next = temp2\n",
    "        #     return preHead.next\n",
    "        \n",
    "        return sortFunc(head, None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "\n",
    "    def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]:\n",
    "        self.merge_sort_by_column(score, k)\n",
    "        return score\n",
    "\n",
    "    def merge_sort_by_column(self, arr, col):\n",
    "        if len(arr) > 1:\n",
    "            mid = len(arr) // 2\n",
    "            left_half = arr[:mid]\n",
    "            right_half = arr[mid:]\n",
    "\n",
    "            # 递归地对左右两半进行归并排序\n",
    "            self.merge_sort_by_column(left_half, col)\n",
    "            self.merge_sort_by_column(right_half, col)\n",
    "\n",
    "            i = j = k = 0\n",
    "\n",
    "            # 归并排序合并操作\n",
    "            while i < len(left_half) and j < len(right_half):\n",
    "                if left_half[i][col] > right_half[j][col]:\n",
    "                    arr[k] = left_half[i]\n",
    "                    i += 1\n",
    "                else:\n",
    "                    arr[k] = right_half[j]\n",
    "                    j += 1\n",
    "                k += 1\n",
    "\n",
    "            while i < len(left_half):\n",
    "                arr[k] = left_half[i]\n",
    "                i += 1\n",
    "                k += 1\n",
    "\n",
    "            while j < len(right_half):\n",
    "                arr[k] = right_half[j]\n",
    "                j += 1\n",
    "                k += 1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "\n",
    "    def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]:\n",
    "        self.merge_sort_by_column(score, k)\n",
    "        return score\n",
    "\n",
    "    def merge_sort_by_column(self, arr, col):\n",
    "        if len(arr) > 1:\n",
    "            mid = len(arr) // 2\n",
    "            left_half = arr[:mid]\n",
    "            right_half = arr[mid:]\n",
    "\n",
    "            # 递归地对左右两半进行归并排序\n",
    "            self.merge_sort_by_column(left_half, col)\n",
    "            self.merge_sort_by_column(right_half, col)\n",
    "\n",
    "            i = j = k = 0\n",
    "\n",
    "            # 归并排序合并操作\n",
    "            while i < len(left_half) and j < len(right_half):\n",
    "                if left_half[i][col] > right_half[j][col]:\n",
    "                    arr[k] = left_half[i]\n",
    "                    i += 1\n",
    "                else:\n",
    "                    arr[k] = right_half[j]\n",
    "                    j += 1\n",
    "                k += 1\n",
    "\n",
    "            if i < len(left_half):\n",
    "                arr[k:] = left_half[i:]\n",
    "            else:\n",
    "                arr[k:] = right_half[j:]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[:] = A[:m] + B\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:] = B\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i=m\n",
    "        j=0\n",
    "        while i<m+n and j<n:\n",
    "            A[i]=B[j]\n",
    "            i+=1\n",
    "            j+=1\n",
    "        return A.sort()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:]=B\n",
    "        A.sort()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i,j = m-1,n-1\n",
    "        idx = m+n-1\n",
    "        while i>=0 or j>=0 :\n",
    "            #print(A)\n",
    "            if i==-1 :\n",
    "                A[idx] = B[j]\n",
    "                idx -= 1\n",
    "                j -= 1\n",
    "            elif j==-1 :\n",
    "                A[idx] = A[i]\n",
    "                idx -= 1\n",
    "                i -= 1\n",
    "            elif A[i]>=B[j] :\n",
    "                A[idx] = A[i]\n",
    "                idx -= 1\n",
    "                i -= 1\n",
    "            else :\n",
    "                A[idx] = B[j]\n",
    "                idx -= 1\n",
    "                j -= 1\n",
    "        \n",
    "                \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        # A[m:] = B\n",
    "        # A.sort()\n",
    "        \n",
    "        if not B:return A\n",
    "        i,j = 0,0\n",
    "        tmp = []\n",
    "        while i<m+n:\n",
    "            if i<m:\n",
    "                tmp.append(A[i])\n",
    "            if j>=n:\n",
    "                break\n",
    "            if not tmp:break\n",
    "            if tmp[0]<B[j]:\n",
    "                A[i] = tmp.pop(0)\n",
    "            else:\n",
    "                A[i] = B[j]\n",
    "                j+=1\n",
    "            i+=1\n",
    "        A[i:]=tmp+B[j:]+A[i+1:m]\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        #特殊情况\n",
    "\n",
    "        insert_index=len(A)-1\n",
    "        n=len(B)-1\n",
    "        m=len(A)-len(B)-1\n",
    "\n",
    "        while n>=0 and m>=0:\n",
    "            if B[n]>=A[m]:\n",
    "                A[insert_index]=B[n]\n",
    "                insert_index-=1\n",
    "                n-=1\n",
    "            else:\n",
    "                A[insert_index]=A[m]\n",
    "                insert_index-=1\n",
    "                m-=1\n",
    "       \n",
    "        for i in range(n+1):\n",
    "            A[i]=B[i]\n",
    "\n",
    "        \n",
    "\n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        A[:]=A[:m]+B\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge1(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(m,m+n):\n",
    "            A[i]=B[i-m]\n",
    "        A.sort()\n",
    "        return A\n",
    "    def merge2(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        new = []\n",
    "        pa, pb = 0, 0\n",
    "        while pa < m or pb < n:\n",
    "            if pa == m:\n",
    "                new.append(B[pb])\n",
    "                pb += 1\n",
    "            elif pb == n:\n",
    "                new.append(A[pa])\n",
    "                pa += 1\n",
    "            elif A[pa] < B[pb]:\n",
    "                new.append(A[pa])\n",
    "                pa += 1\n",
    "            else:\n",
    "                new.append(B[pb])\n",
    "                pb += 1\n",
    "        A[:] = new\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        la=m-1\n",
    "        lb=n-1\n",
    "        tail=m+n-1\n",
    "        while tail>=0:\n",
    "            if la<0:\n",
    "                A[tail]=B[lb]\n",
    "                lb-=1\n",
    "                tail-=1\n",
    "            elif lb<0:\n",
    "                A[tail]=A[la]\n",
    "                la-=1\n",
    "                tail-=1\n",
    "            elif A[la]>B[lb]:\n",
    "                A[tail]=A[la]\n",
    "                la-=1\n",
    "                tail-=1\n",
    "            else:\n",
    "                A[tail]=B[lb]\n",
    "                lb-=1\n",
    "                tail-=1\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:] = B\n",
    "        A.sort()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(m,len(A)):\n",
    "            A[i] = B[i-m]\n",
    "        return A.sort()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[:] =A[:m] + B\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i,j = m-1,n-1\n",
    "        cur = m+n-1\n",
    "        while i >= 0 and j >= 0:\n",
    "            if A[i] < B[j]:\n",
    "                A[cur] = B[j]\n",
    "                cur -= 1\n",
    "                j -= 1\n",
    "            else:\n",
    "                A[cur] = A[i]\n",
    "                cur -= 1\n",
    "                i -= 1\n",
    "        if j != -1:\n",
    "            A[:j+1] = B[:j+1]\n",
    "        return A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        for i in range(m, m+n):\n",
    "            A[i] = B[i-m]\n",
    "        A.sort()\n",
    "        return A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        r = m-1\n",
    "        l = n-1\n",
    "        while r>=0 and l>=0:\n",
    "            if A[r]>=B[l]:\n",
    "                A[r+l+1] = A[r]\n",
    "                r -= 1\n",
    "            else:\n",
    "                A[r+l+1] = B[l]\n",
    "                l -= 1\n",
    "        \n",
    "        while l>=0:\n",
    "            A[l] = B[l]\n",
    "            l -= 1\n",
    "\n",
    "        return A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i, j = m-1, n-1\n",
    "        p = m + n - 1\n",
    "        for k in range(p, -1, -1):\n",
    "            # print(k)\n",
    "            if i >= 0 and j >= 0:\n",
    "                # print(A, B)\n",
    "                if A[i] > B[j]:\n",
    "                    A[k] = A[i]\n",
    "                    i -= 1\n",
    "                else:\n",
    "                    A[k] = B[j]\n",
    "                    j -= 1\n",
    "        if j != -1:\n",
    "            A[:j+1] = B[:j+1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        A[m:] = B  # 将A末端的缓冲空间留给B\n",
    "        A.sort()  # A记为合并排序的数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:] = B\n",
    "\n",
    "        A.sort()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "\tdef merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "\t\t\"\"\"\n",
    "\t\tDo not return anything, modify A in-place instead.\n",
    "\t\t\"\"\"\n",
    "\t\tfor i in range(n):\n",
    "\t\t\tA[m + i] = B[i]\n",
    "\t\tA.sort()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        buffer_size = len(A) - m\n",
    "        for i in range(m, m+ buffer_size):\n",
    "            A[i] = B[i-m]\n",
    "        A.sort()\n",
    "        return A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        idx1 = m - 1\n",
    "        idx2 = n - 1\n",
    "        cur = m + n - 1\n",
    "        while idx1 > -1 and idx2 > -1:\n",
    "            if A[idx1] < B[idx2]:\n",
    "                A[cur] = B[idx2]\n",
    "                idx2 -= 1\n",
    "            else:\n",
    "                A[cur] = A[idx1]\n",
    "                idx1 -= 1\n",
    "            cur -= 1\n",
    " \n",
    "        while idx2 > -1: A[cur] = B[idx2] ; idx2-=1;cur-=1\n",
    "        return A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        while m>0 and n>0:\n",
    "            if A[m-1]>B[n-1]:\n",
    "                A[m+n-1] = A[m-1]\n",
    "                m-=1\n",
    "            else:\n",
    "                A[m+n-1] = B[n-1]\n",
    "                n-=1\n",
    "        if n: A[:n] = B[:n]\n",
    "        return A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i1, i2 = m - 1, n - 1\n",
    "        for i in range(m + n - 1, -1, -1):\n",
    "            if i2 >= 0 and (i1 == -1 or nums2[i2] > nums1[i1]):\n",
    "                nums1[i] = nums2[i2]\n",
    "                i2 -= 1\n",
    "            else:\n",
    "                nums1[i] = nums1[i1]\n",
    "                i1 -= 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i=m-1\n",
    "        j=n-1\n",
    "        k=m+n-1\n",
    "        while i>=0 and j>=0:\n",
    "            if A[i]>=B[j]:\n",
    "                A[k]=A[i]\n",
    "                i-=1\n",
    "                k-=1\n",
    "            else:\n",
    "                A[k]=B[j]\n",
    "                k-=1\n",
    "                j-=1\n",
    "        if j>=0:\n",
    "            A[:k+1]=B[:j+1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        idx1=m-1\n",
    "        idx2=n-1\n",
    "        cur=m+n-1\n",
    "        while idx1>-1 and idx2>-1:\n",
    "            if A[idx1]<B[idx2]:\n",
    "                A[cur]=B[idx2]\n",
    "                cur-=1\n",
    "                idx2-=1\n",
    "            else:\n",
    "                A[cur]=A[idx1]\n",
    "                cur-=1\n",
    "                idx1-=1\n",
    "        if idx2!=-1:\n",
    "            A[:idx2+1]=B[:idx2+1]\n",
    "        return A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        sorted = []\n",
    "        pa, pb = 0, 0\n",
    "\n",
    "        while pa < m or pb < n:\n",
    "            if pa == m:\n",
    "                sorted.append(B[pb])\n",
    "                pb += 1\n",
    "            elif pb == n:\n",
    "                sorted.append(A[pa])\n",
    "                pa += 1\n",
    "            elif A[pa] < B[pb]:\n",
    "                sorted.append(A[pa])\n",
    "                pa += 1\n",
    "            else:\n",
    "                sorted.append(B[pb])\n",
    "                pb += 1\n",
    "        # 数组的切片操作，替换整个数组\n",
    "        A[:] = sorted"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        k=m+n-1\n",
    "        i=m-1\n",
    "        j=n-1\n",
    "        while i>=0 and j>=0:\n",
    "            if A[i]<=B[j]:\n",
    "                A[k]=B[j]\n",
    "                j-=1\n",
    "                k-=1\n",
    "            else:\n",
    "                A[k]=A[i]\n",
    "                i-=1\n",
    "                k-=1\n",
    "        if j>=0:\n",
    "            A[:k+1]=B[:j+1]\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        a=m\n",
    "        b=n\n",
    "        while m<a+b:\n",
    "            A[m]=B[n-1]\n",
    "            m+=1\n",
    "            n-=1\n",
    "        return A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        aa = A[0:m]\n",
    "        A.clear()\n",
    "        A.extend(aa)\n",
    "        # print(A)\n",
    "        A.extend(B)\n",
    "        # print(A)\n",
    "        A.sort()\n",
    "        # print(A)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:] = B\n",
    "        A.sort()\n",
    "        return A\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# ### my:双指针 v1 40/59---pass 【0】 0，【1】1 not pass\n",
    "# class Solution:\n",
    "#     def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "#         \"\"\"\n",
    "#         Do not return anything, modify A in-place instead.\n",
    "#         \"\"\"\n",
    "#         i,j=m-1,n-1\n",
    "#         for k in range(m+n-1,-1,-1):\n",
    "#             if i>=0 and j>=0:\n",
    "#                 if B[j]>A[i]:\n",
    "#                     A[k]=B[j]\n",
    "#                     j-=1\n",
    "#                 else:\n",
    "#                     A[k]=A[i]\n",
    "#                     i-=1\n",
    "#             else:\n",
    "#                 break\n",
    "#         return A\n",
    "\n",
    "### my:双指针 v1 40/59---pass 【0】 0，【1】1 not pass\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        # if m==0:\n",
    "        #     # A=B\n",
    "        #     return B\n",
    "        # if n==0:\n",
    "        #     return A\n",
    "        i,j=m-1,n-1\n",
    "        for k in range(m+n-1,-1,-1):\n",
    "            if i>=0 and j>=0:\n",
    "                if B[j]>A[i]:\n",
    "                    A[k]=B[j]\n",
    "                    j-=1\n",
    "                else:\n",
    "                    A[k]=A[i]\n",
    "                    i-=1\n",
    "            else:\n",
    "                break\n",
    "        if j>=0:\n",
    "            A[:j+1]=B[:j+1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        index1 = m-1\n",
    "        index2 = n-1\n",
    "        while index1+index2+1>=0:\n",
    "            if (index2<0) or ((index1>=0) and (A[index1]>B[index2])):\n",
    "                A[index1+index2+1] = A[index1]\n",
    "                index1 -= 1\n",
    "            else:\n",
    "                A[index1+index2+1] = B[index2]\n",
    "                index2 -= 1 \n",
    "            # print(index1, index2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        c=[]\n",
    "        i,j=0,0\n",
    "        while i<m and j<n:\n",
    "            if A[i]<B[j]:\n",
    "                c.append(A[i])\n",
    "                i+=1\n",
    "            else:\n",
    "                c.append(B[j])\n",
    "                j+=1\n",
    "        if i<m:\n",
    "            c.extend(A[i:m])\n",
    "        elif j<n:\n",
    "            c.extend(B[j:n])\n",
    "        print(c)\n",
    "        A[:]=c[:]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        # A[m:] = B\n",
    "        # A.sort()\n",
    "        if not B:return A\n",
    "        i,j = 0,0\n",
    "        tmp = []\n",
    "        while i<m+n:\n",
    "            if i<m:\n",
    "                tmp.append(A[i])\n",
    "            if j>=n:\n",
    "                break\n",
    "            if not tmp:break\n",
    "            if tmp[0]<B[j]:\n",
    "                A[i] = tmp.pop(0)\n",
    "            else:\n",
    "                A[i] = B[j]\n",
    "                j+=1\n",
    "            i+=1\n",
    "        # print(A,tmp,i,j)\n",
    "        A[i:]=tmp+B[j:]+A[i+1:m]\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i, j = m-1, n-1\n",
    "        p = m + n - 1\n",
    "        while i >= 0 and j >= 0:\n",
    "            # print(A, B)\n",
    "            if A[i] > B[j]:\n",
    "                A[p] = A[i]\n",
    "                i -= 1\n",
    "                p -= 1\n",
    "            else:\n",
    "                A[p] = B[j]\n",
    "                j -= 1\n",
    "                p -= 1\n",
    "        if j != -1:\n",
    "            A[:j+1] = B[:j+1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        while m-1>=0 and n-1>=0:\n",
    "            if A[m-1]>B[n-1]:\n",
    "                A[m+n-1] = A[m-1]\n",
    "                m-=1\n",
    "            else:\n",
    "                A[m+n-1] = B[n-1]\n",
    "                n-=1\n",
    "        if n>=0 :A[:n] = B[:n]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:] = B\n",
    "        A.sort()\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m: m + n + 1] = B\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "\n",
    "        A[m:] = B\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:] = B\n",
    "        A.sort()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:]=B\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        l = m\n",
    "        i = j = 0\n",
    "        \n",
    "        while j < n and i < m + n:\n",
    "            if B[j] < A[i] or (i >= l):\n",
    "                A.insert(i, B[j])\n",
    "                j += 1\n",
    "                l += 1\n",
    "                A.pop()\n",
    "            i += 1\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i, j = m-1, n-1\n",
    "        p = m + n - 1\n",
    "        for k in range(p, -1, -1):\n",
    "            print(k)\n",
    "            if i >= 0 and j >= 0:\n",
    "                print(A, B)\n",
    "                if A[i] > B[j]:\n",
    "                    A[k] = A[i]\n",
    "                    i -= 1\n",
    "                else:\n",
    "                    A[k] = B[j]\n",
    "                    j -= 1\n",
    "        if j != -1:\n",
    "            A[:j+1] = B[:j+1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        pa, pb = m - 1, n - 1\n",
    "        tail = m + n - 1\n",
    "        while pa >= 0 or pb >= 0:\n",
    "            if pa == -1:\n",
    "                A[tail] = B[pb]\n",
    "                pb -= 1\n",
    "            elif pb == -1:\n",
    "                A[tail] = A[pa]\n",
    "                pa -= 1\n",
    "            elif A[pa] > B[pb]:\n",
    "                A[tail] = A[pa]\n",
    "                pa -= 1\n",
    "            else:\n",
    "                A[tail] = B[pb]\n",
    "                pb -= 1\n",
    "            tail -= 1\n",
    "        return A\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        index = len(A) - 1\n",
    "        while m > 0 and n > 0:\n",
    "            if B[n - 1] > A[m - 1]:\n",
    "                A[index] = B[n - 1]\n",
    "                n -= 1\n",
    "            else:\n",
    "                A[index] = A[m - 1]\n",
    "                m -= 1\n",
    "            index -= 1\n",
    "        for i in range(n):\n",
    "            A[i] = B[i]\n",
    "        return A\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(len(B)):\n",
    "            A.pop()\n",
    "\n",
    "        pa = 0\n",
    "        for pb in range(len(B)):\n",
    "            while pa < len(A):\n",
    "                if B[pb] < A[pa]:\n",
    "                    A.insert(pa, B[pb])\n",
    "                    break\n",
    "                pa += 1\n",
    "            if pa == len(A):\n",
    "                A.append(B[pb])\n",
    "                pa += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:] = B\n",
    "        # A = A[0:m] + B\n",
    "        A.sort()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i, j, k = m-1, n-1, m+n-1\n",
    "        while i >= 0 or j >= 0:\n",
    "            if i >= 0 and j >= 0:\n",
    "                if A[i] >= B[j]:\n",
    "                    A[k] = A[i]\n",
    "                    k -= 1\n",
    "                    i -= 1\n",
    "                else:\n",
    "                    A[k] = B[j]\n",
    "                    k -= 1\n",
    "                    j -= 1\n",
    "            elif i < 0:\n",
    "                A[:k+1] = B[:j+1]\n",
    "                break\n",
    "            else:\n",
    "                break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:] = B[:]\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:]=B\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        sorted = []\n",
    "        pa, pb = 0, 0\n",
    "        while pa < m or pb < n:\n",
    "            if pa == m:\n",
    "                sorted.append(B[pb])\n",
    "                pb += 1\n",
    "            elif pb == n:\n",
    "                sorted.append(A[pa])\n",
    "                pa += 1\n",
    "            elif A[pa] < B[pb]:\n",
    "                sorted.append(A[pa])\n",
    "                pa += 1\n",
    "            else:\n",
    "                sorted.append(B[pb])\n",
    "                pb += 1\n",
    "        A[:] = sorted"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(n):\n",
    "            A[m+i]=B[i]\n",
    "        A.sort()\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        res = []\n",
    "        pa, pb = 0,0\n",
    "        while pa < m or pb < n:\n",
    "            if pa == m:\n",
    "                res.append(B[pb])\n",
    "                pb +=1\n",
    "            elif pb == n:\n",
    "                res.append(A[pa])\n",
    "                pa +=1\n",
    "            elif A[pa] < B[pb]:\n",
    "                res.append(A[pa])\n",
    "                pa +=1\n",
    "            else:\n",
    "                res.append(B[pb])\n",
    "                pb +=1\n",
    "        A[:] = res[:]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        cur = len(A) - 1\n",
    "        pa = m - 1\n",
    "        pb = n - 1\n",
    "        while pa >= 0 and pb >= 0:\n",
    "            if B[pb] > A[pa]:\n",
    "                A[cur] = B[pb]\n",
    "                pb -= 1 \n",
    "            else:\n",
    "                A[cur] = A[pa]\n",
    "                pa -= 1 \n",
    "            cur -= 1\n",
    "\n",
    "        while pb >= 0:\n",
    "            A[pb] = B[pb]\n",
    "            pb -= 1\n",
    "\n",
    "        return A \n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        if m==0:A[:]=B\n",
    "        if m and n:\n",
    "            A[:]=A[:m]\n",
    "            A.extend(B)\n",
    "            A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(n):\n",
    "            A[m+i] = B[i]\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:] = B\n",
    "        A.sort()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[m:] = B\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i, m ,n = -1, m-1, n-1\n",
    "        while m>=0 and n>=0:\n",
    "            if A[m] > B[n]:\n",
    "                A[i] = A[m]\n",
    "                m -= 1\n",
    "            else:\n",
    "                A[i] = B[n]\n",
    "                n -= 1\n",
    "            i -= 1\n",
    "        if m<0:\n",
    "            while n>=0:\n",
    "                A[i] = B[n]\n",
    "                n -= 1\n",
    "                i -= 1\n",
    "        else:\n",
    "            while m>=0:\n",
    "                A[i] = A[m]\n",
    "                m -= 1\n",
    "                i -= 1\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        index_a = 0\n",
    "        index_b = 0\n",
    "        swap_cnt =0\n",
    "        if len(A) ==0:\n",
    "            return B\n",
    "        if len(B) == 0:\n",
    "            return A\n",
    "        while index_a < len(A) and index_b < len(B):\n",
    "            if index_a < swap_cnt + m and A[index_a] < B[index_b]:\n",
    "                index_a +=1\n",
    "            elif index_a >= swap_cnt+m or swap_cnt==n:\n",
    "                break\n",
    "            elif A[index_a] >= B[index_b]:\n",
    "                A[index_a+1:] = A[index_a:-1]\n",
    "                A[index_a] = B[index_b]\n",
    "                index_b+=1\n",
    "                index_a+=1\n",
    "                swap_cnt+=1\n",
    "        if swap_cnt!=n:\n",
    "            A[index_a:] = B[index_b:]\n",
    "\n",
    "        return A\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution(object):\n",
    "    def merge(self, A, m, B, n):\n",
    "        k=m+n-1\n",
    "        i,j=m-1,n-1\n",
    "        while i>=0 and j>=0:\n",
    "            if A[i]>=B[j]:\n",
    "                A[k]=A[i]\n",
    "                k-=1\n",
    "                i-=1\n",
    "            else:\n",
    "                A[k]=B[j]\n",
    "                k-=1\n",
    "                j-=1\n",
    "        # 如果j=-1,也就是 j走到 0，B全移到 A 里面了，那 A就不需要处理。只需要判断当 B 没有全移动到 A 里面去的情况  \n",
    "        if j!=-1:\n",
    "            A[:j+1]=B[:j+1]\n",
    "        return A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(n):\n",
    "            q = A.pop(-1)\n",
    "        for i in range(n):\n",
    "            A.append(B.pop(0))\n",
    "        n = len(A)\n",
    "        for i in range(n):\n",
    "            min_l = i\n",
    "            for j in range(i + 1, n):\n",
    "                if A[j] < A[min_l]:\n",
    "                    min_l = j\n",
    "            A[i], A[min_l] = A[min_l], A[i]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(m, (m + n)):\n",
    "            A[i] = B[i - m]\n",
    "        A.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i = m-1\n",
    "        j = n-1\n",
    "        index = m+n-1\n",
    "\n",
    "        while i>=0 and j>=0:\n",
    "            if A[i]>B[j]:\n",
    "                A[index] =  A[i]\n",
    "                i-=1\n",
    "            else:\n",
    "                A[index] = B[j]\n",
    "                j-=1\n",
    "            \n",
    "            index -=1\n",
    "\n",
    "        while j>=0:\n",
    "            A[index] = B[j]\n",
    "            j-=1\n",
    "            index -=1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "\n",
    "        Ai = m-1\n",
    "        Bi = n-1\n",
    "\n",
    "        while(Ai >= 0 and Bi >= 0):\n",
    "            if A[Ai] < B[Bi]:\n",
    "                A[Ai+Bi+1] = B[Bi]\n",
    "                Bi -= 1\n",
    "            else:\n",
    "                A[Ai+Bi+1] = A[Ai]\n",
    "                Ai -= 1\n",
    "\n",
    "        # 如果A还剩下元素，由于已经是排好序的了，因此不需要操作，只用看B的\n",
    "        while Bi >= 0:\n",
    "            A[Ai+Bi+1] = B[Bi]\n",
    "            Bi -= 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        A[:] = A[:m] + B\n",
    "        A[:]=self.sortArray(A)\n",
    "    def sortArray(self, nums: List[int]) -> List[int]:\n",
    "        if len(nums) <= 1:\n",
    "            return nums\n",
    "        mid = len(nums) // 2\n",
    "        left = self.sortArray(nums[:mid])\n",
    "        right = self.sortArray(nums[mid:])\n",
    "        A = self.merge_sort(left, right)\n",
    "        return A\n",
    "\n",
    "    def merge_sort(self,left, right):\n",
    "        result = []\n",
    "        i = j = 0\n",
    "        while i < len(left) and j < len(right):\n",
    "            if left[i] < right[j]:\n",
    "                result.append(left[i])\n",
    "                i += 1\n",
    "            else:\n",
    "                result.append(right[j])\n",
    "                j += 1\n",
    "        result += left[i:]\n",
    "        result += right[j:]\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        endA,endB,end = m-1,n-1,m+n-1\n",
    "        while endA >= 0 and endB >= 0:\n",
    "            if A[endA] > B[endB]:\n",
    "                A[end] = A[endA]\n",
    "                endA -= 1\n",
    "                end -= 1\n",
    "            else:\n",
    "                A[end] = B[endB]\n",
    "                endB -= 1\n",
    "                end -= 1\n",
    "        \n",
    "        while endB >= 0:\n",
    "            A[end] = B[endB]\n",
    "            end -= 1\n",
    "            endB -= 1\n",
    "        return A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify A in-place instead.\n",
    "        \"\"\"\n",
    "        i,j,ipass = 0,0,0\n",
    "        while ipass < m and j < n:\n",
    "            if A[i] >= B[j]:\n",
    "                A.insert(i, B[j])\n",
    "                A.pop()\n",
    "                j += 1\n",
    "                i += 1\n",
    "            else:\n",
    "                i += 1\n",
    "                ipass += 1\n",
    "        if ipass == m:\n",
    "            A[i:] = B[j:].copy()"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
